How to avoid scientific notation for large numbers in JavaScript?

后端 未结 22 2552
無奈伤痛
無奈伤痛 2020-11-22 00:31

JavaScript converts a large INT to scientific notation when the number becomes large. How can I prevent this from happening?

22条回答
  •  半阙折子戏
    2020-11-22 00:57

    I think there may be several similar answers, but here's a thing I came up with

    // If you're gonna tell me not to use 'with' I understand, just,
    // it has no other purpose, ;( andthe code actually looks neater
    // 'with' it but I will edit the answer if anyone insists
    var commas = false;
    
    function digit(number1, index1, base1) {
        with (Math) {
            return floor(number1/pow(base1, index1))%base1;
        }
    }
    
    function digits(number1, base1) {
        with (Math) {
            o = "";
            l = floor(log10(number1)/log10(base1));
            for (var index1 = 0; index1 < l+1; index1++) {
                o = digit(number1, index1, base1) + o;
                if (commas && i%3==2 && i

    Note: this is only as accurate as the javascript math functions and has problems when using log instead of log10 on the line before the for loop; it will write 1000 in base-10 as 000 so I changed it to log10 because people will mostly be using base-10 anyways.

    This may not be a very accurate solution but I'm proud to say it can successfully translate numbers across bases and comes with an option for commas!

提交回复
热议问题