我试图在JavaScript中打印一个整数,用逗号作为千位分隔符。例如,我想将数字1234567显示为“1234567”。我该怎么做?
我是这样做的:
函数编号WithCommas(x){x=x.toString();var模式=/(-?\d+)(\d{3})/;while(模式测试(x))x=x.replace(模式,“$1,$2”);返回x;}console.log(数字与逗号(1000))
有没有更简单或更优雅的方法?如果它也可以与浮点运算一起使用,那就很好了,但这不是必须的。它不需要特定于区域设置来决定句点和逗号。
我找到了一种适用于所有情况的方法。CodeSandbox示例
function commas(n) {
if (n < 1000) {
return n + ''
} else {
// Convert to string.
n += ''
// Skip scientific notation.
if (n.indexOf('e') !== -1) {
return n
}
// Support fractions.
let i = n.indexOf('.')
let f = i == -1 ? '' : n.slice(i)
if (f) n = n.slice(0, i)
// Add commas.
i = n.length
n = n.split('')
while (i > 3) n.splice((i -= 3), 0, ',')
return n.join('') + f
}
}
这就像诺亚·弗雷塔斯(Noah Freitas)的答案,但支持分数和科学记数法。
我认为如果性能不受关注,toLocaleString是最好的选择。
edit:这里有一个CodeSandbox,其中包含一些示例:https://codesandbox.io/s/zmvxjpj6x
我在早些时候找到了这个答案,我更新了它以允许负数。
您可以在将数字转换为字符串后使用它。
删除额外的小数位数只是为了方便,因为这是一种非常常见的情况。如果不需要,可以跳过它。
// Keep only digits, hyphen and decimal points:
myNum.toString() .replace(/[^-\d.]/g, "")
// Remove duplicated decimal point, if one exists:
.replace(/^(\d*\.)(.*)\.(.*)$/, '$1$2$3')
// Keep only two digits past the decimal point:
.replace(/\.(\d{2})\d+/, '.$1')
// Add thousands separators:
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
我在Aki143S的解决方案中添加了tofixed。此解决方案使用点表示千位分隔符,使用逗号表示精度。
function formatNumber( num, fixed ) {
var decimalPart;
var array = Math.floor(num).toString().split('');
var index = -3;
while ( array.length + index > 0 ) {
array.splice( index, 0, '.' );
index -= 4;
}
if(fixed > 0){
decimalPart = num.toFixed(fixed).split(".")[1];
return array.join('') + "," + decimalPart;
}
return array.join('');
};
示例;
formatNumber(17347, 0) = 17.347
formatNumber(17347, 3) = 17.347,000
formatNumber(1234563.4545, 3) = 1.234.563,454
@user1437663的解决方案很棒。
真正理解解决方案的人是准备好理解复杂的正则表达式。
一个小的改进使它更易读:
function numberWithCommas(x) {
var parts = x.toString().split(".");
return parts[0].replace(/\B(?=(\d{3})+(?=$))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
该模式以\B开头,以避免在单词开头使用逗号。有趣的是,模式返回为空,因为\B不前进“游标”(这同样适用于$)。
O\B后面跟着一个鲜为人知的资源,但这是Perl正则表达式的一个强大功能。
Pattern1 (? = (Pattern2) ).
神奇的是,括号(Pattern2)中的内容是一个模式,它遵循先前的模式(Pattern1),但不前进光标,也不是返回的模式的一部分。这是一种未来模式。当有人向前看但真的不走路时,这是类似的!
在这种情况下,模式2是
\d{3})+(?=$)
它表示3位数字(一次或多次),后跟字符串结尾($)
最后,Replace方法将找到的所有模式(空字符串)更改为逗号。这仅在剩余部分是3位数的倍数时发生(未来光标到达原点末端的情况)。
另一种方式,支持小数、不同的分隔符和负号。
var number_format = function(number, decimal_pos, decimal_sep, thousand_sep) {
var ts = ( thousand_sep == null ? ',' : thousand_sep )
, ds = ( decimal_sep == null ? '.' : decimal_sep )
, dp = ( decimal_pos == null ? 2 : decimal_pos )
, n = Math.floor(Math.abs(number)).toString()
, i = n.length % 3
, f = ((number < 0) ? '-' : '') + n.substr(0, i)
;
for(;i<n.length;i+=3) {
if(i!=0) f+=ts;
f+=n.substr(i,3);
}
if(dp > 0)
f += ds + parseFloat(number).toFixed(dp).split('.')[1]
return f;
}
@Jignesh Sanghani的一些更正,别忘了对他的评论投赞成票。