2

I use one small code js to add comma to value:

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

I have problem when try to add comma to big values like sextillion values. Eg.

addCommas(1000000) //return correct "1,000,000"

but if use big values like this

addCommas(50949024266983356472874) // return wrong "5.094902426698335e+22"

What or where I do wrong?

Prince John Wesley
  • 62,492
  • 12
  • 87
  • 94
  • I found this with seems kind of relevant but might not be very helpful: [How to avoid scientific notation for large numbers in javascript?](http://stackoverflow.com/questions/1685680/how-to-avoid-scientific-notation-for-large-numbers-in-javascript) – Felix Kling Nov 29 '12 at 17:00

3 Answers3

2

Your input might already be a float. Numbers larger than 2^32 tend to be like this. Make sure your input is a string and your function will run fine.

JavaScript doesn't have int and float types. Instead it just has a Number type and it will decide on it's own when to use which.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
1

When you do

nStr += '';

You're asking javascript to first convert your number to a string. That's when it decides to write it as "5.094902426698335e+22". The problem isn't in the rest of your algorithm.

The conversion is described here in ecmascript

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

If your number is stored in a string the following function will achieve what you are asking for.

function addCommas( txtNum ) {
    var parts = txtNum.split(".");
    parts[0] = parts[0].reverse().replace(/(\d{3})/g, "$1,").reverse();
    return parts.join(".");
}   

String.prototype.reverse = function () {
    return this.split("").reverse().join("");
}

addCommas( "-50000000000000000000000000000000000000000.0000" );
// => -50,000,000,000,000,000,000,000,000,000,000,000,000,000.0000
Bruno
  • 5,772
  • 1
  • 26
  • 43