[英]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”
但是,我想忽略美分/小數,因此我嘗試了如下所示的替代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);
}
addCommas()和addCommasRound()之間的唯一區別是將MathRound()插入return語句中。 為什么這會導致該值為“ NaN”而不是“ 1,838,205”?
我還嘗試將最后一行更改為:
return Math.round(x1);
...只是看它是否不會失敗,但結果相同(“ NaN”)。
因為x1
和x2
不是數字(NaN代表數字),所以它們是字符串。
您需要先將數字四舍五入,然后再執行字符串操作。
function addCommasRound(nStr) {
nStr = String(Math.round(Number(nStr)));
另請參見JavaScript字符串和數字轉換 。
數字文字中不允許使用逗號。 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, '$1' + ',' + '$2');
}
return x1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.