为什么我尝试四舍五入时得到 NaN (javascript)?
Why am I getting NaN with this attempt at rounding (javascript)?
我有这段代码可以在 Chart.JS 条形图中的条形上方添加一个值:
//ctx.fillText(addCommas(dataset.data[i]), model.x, y_pos);
ctx.fillText(addCommasRound(dataset.data[i]), model.x, y_pos);
旧代码(使用 addCommas())有效,将“1838204.79”等值更改为“1,838,204.79”
不过,我想忽略 cents/decimals,所以我尝试了另一种 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, '' + ',' + '');
}
return Math.round(x1 + x2);
}
addCommas() 和 addCommasRound() 之间的唯一区别是在 return 语句中插入了 MathRound()。为什么这会导致值为 "NaN" 而不是“1,838,205”?
我还尝试将最后一行更改为:
return Math.round(x1);
...只是为了看看它是否不会失败,但结果相同 ("NaN")。
因为x1
和x2
不是数字(NaN代表什么),它们是字符串。
您需要先对数字进行四舍五入,然后再进行字符串运算。
function addCommasRound(nStr) {
nStr = String(Math.round(Number(nStr)));
另见 JavaScript string and number conversion。
数字文字中不允许使用逗号。 Math.round
尝试将参数转换为数字。
执行 +'1,000'
产生 NaN
,而 +'1000'
产生 1000
.
如果您想在要返回的数字中添加逗号,请先四舍五入,然后然后添加逗号。
根据 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, '' + ',' + '');
}
return x1;
}
我有这段代码可以在 Chart.JS 条形图中的条形上方添加一个值:
//ctx.fillText(addCommas(dataset.data[i]), model.x, y_pos);
ctx.fillText(addCommasRound(dataset.data[i]), model.x, y_pos);
旧代码(使用 addCommas())有效,将“1838204.79”等值更改为“1,838,204.79”
不过,我想忽略 cents/decimals,所以我尝试了另一种 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, '' + ',' + '');
}
return Math.round(x1 + x2);
}
addCommas() 和 addCommasRound() 之间的唯一区别是在 return 语句中插入了 MathRound()。为什么这会导致值为 "NaN" 而不是“1,838,205”?
我还尝试将最后一行更改为:
return Math.round(x1);
...只是为了看看它是否不会失败,但结果相同 ("NaN")。
因为x1
和x2
不是数字(NaN代表什么),它们是字符串。
您需要先对数字进行四舍五入,然后再进行字符串运算。
function addCommasRound(nStr) {
nStr = String(Math.round(Number(nStr)));
另见 JavaScript string and number conversion。
数字文字中不允许使用逗号。 Math.round
尝试将参数转换为数字。
执行 +'1,000'
产生 NaN
,而 +'1000'
产生 1000
.
如果您想在要返回的数字中添加逗号,请先四舍五入,然后然后添加逗号。
根据 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, '' + ',' + '');
}
return x1;
}