简体   繁体   English

为什么尝试四舍五入会出现NaN(javascript)?

[英]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: 我有以下代码可在Chart.JS条形图中的条形上方添加一个值:

//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" 旧代码(使用addCommas())有效,将“ 1838204.79”之类的值更改为“ 1,838,204.79”

I want to ignore the cents/decimals, though, so I tried an alternative addCommasRound() method like this: 但是,我想忽略美分/小数,因此我尝试了如下所示的替代addCommasRound()方法:

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. addCommas()和addCommasRound()之间的唯一区别是将MathRound()插入return语句中。 Why does this cause the value to be "NaN" instead of "1,838,205"? 为什么这会导致该值为“ NaN”而不是“ 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. ...只是看它是否不会失败,但结果相同(“ NaN”)。

Because x1 and x2 are not numbers (which is what NaN stands for), they are strings. 因为x1x2不是数字(NaN代表数字),所以它们是字符串。

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 . 另请参见JavaScript字符串和数字转换

Commas are not allowed in numeric literals. 数字文字中不允许使用逗号。 Math.round attempts to convert the parameters to numbers. Math.round尝试将参数转换为数字。

Executing +'1,000' produces NaN , whereas +'1000' produces 1000 . 执行+'1,000'产生NaN ,而+'1000'产生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: 根据OrangeDog的答案,我得出了这个可行的推导:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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