B. Clay Shannon - 6 months ago 27

Javascript Question

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.

Answer

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.