1

I've got this code to add a value above a bar in a Chart.JS bar chart:

//ctx.fillText(addCommas(dataset.data[i]), model.x, y_pos);
ctx.fillText(addCommasRound(dataset.data[i]), model.x, y_pos);

The old code (using addCommas()) worked, changing values such as "1838204.79" to "1,838,204.79"

I want to ignore the cents/decimals, though, so I tried an alternative addCommasRound() method like this:

function addCommasRound(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 Math.round(x1 + x2);
}

The only difference between addCommas() and addCommasRound() is the insertion of MathRound() into the return statement. Why does this cause the value to be "NaN" instead of "1,838,205"?

I also tried changing the last line to:

return Math.round(x1);

...just to see if it would not fail, but with the same ("NaN") result.

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

3 Answers3

3

Commas are not allowed in numeric literals. Math.round attempts to convert the parameters to numbers.

Executing +'1,000' produces NaN, whereas +'1000' produces 1000.

If you want to add commas to the numbers you're returning, round first, and then add commas.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
2

Because x1 and x2 are not numbers (which is what NaN stands for), they are strings.

You need to round the number first, then perform the string operations.

function addCommasRound(nStr) {
    nStr = String(Math.round(Number(nStr)));

See also JavaScript string and number conversion.

Community
  • 1
  • 1
OrangeDog
  • 36,653
  • 12
  • 122
  • 207
-1

Based on OrangeDog's answer, I came up with this working derivation:

function addCommasRound(nStr) {
    nStr = String(Math.round(Number(nStr)));
    x = nStr.split('.');
    x1 = x[0];
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1;
}
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862