简体   繁体   中英

Why am I getting NaN with this attempt at rounding (javascript)?

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.

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 .

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM