我试图在JavaScript中打印一个整数,用逗号作为千位分隔符。例如,我想将数字1234567显示为“1234567”。我该怎么做?
我是这样做的:
函数编号WithCommas(x){x=x.toString();var模式=/(-?\d+)(\d{3})/;while(模式测试(x))x=x.replace(模式,“$1,$2”);返回x;}console.log(数字与逗号(1000))
有没有更简单或更优雅的方法?如果它也可以与浮点运算一起使用,那就很好了,但这不是必须的。它不需要特定于区域设置来决定句点和逗号。
我想我应该分享一个小技巧,我正在使用它来格式化大数字。我没有插入逗号或空格,而是在“千”之间插入一个空的但可见的跨度。这使得数千个输入很容易看到,但它允许以原始格式复制/粘贴输入,不使用逗号/空格。
// This function accepts an integer, and produces a piece of HTML that shows it nicely with
// some empty space at "thousand" markers.
// Note, these space are not spaces, if you copy paste, they will not be visible.
function valPrettyPrint(orgVal) {
// Save after-comma text, if present
var period = orgVal.indexOf(".");
var frac = period >= 0 ? orgVal.substr(period) : "";
// Work on input as an integer
var val = "" + Math.trunc(orgVal);
var res = "";
while (val.length > 0) {
res = val.substr(Math.max(0, val.length - 3), 3) + res;
val = val.substr(0, val.length - 3);
if (val.length > 0) {
res = "<span class='thousandsSeparator'></span>" + res;
}
}
// Add the saved after-period information
res += frac;
return res;
}
使用此CSS:
.thousandsSeparator {
display : inline;
padding-left : 4px;
}
请参见示例JSFiddle。
对于任何喜欢1行和单个正则表达式,但不想使用split()的人,这里有一个来自其他答案的正则表达式的增强版本,它处理(忽略)小数点:
var formatted = (x+'').replace(/(\..*)$|(\d)(?=(\d{3})+(?!\d))/g, (digit, fract) => fract || digit + ',');
正则表达式首先匹配以文字“.”开头的子字符串,并将其替换为自身(“fract”),然后匹配任何数字,后跟3位数的倍数,并将“,”放在其后。
例如,x=12345678.12345678将给出formated=“12345678.12345 678”。
我的答案是唯一一个完全用更明智的选择替代jQuery的答案:
function $(dollarAmount)
{
const locale = 'en-US';
const options = { style: 'currency', currency: 'USD' };
return Intl.NumberFormat(locale, options).format(dollarAmount);
}
此解决方案不仅添加了逗号,而且在您输入金额如$(1000.9999)时,它还舍入到最接近的一分钱,您将获得1001.00美元。此外,您输入的值可以是数字或字符串;没关系。
如果您正在处理货币,但不希望金额上显示前导美元符号,您也可以添加此函数,该函数使用前一个函数,但删除$:
function no$(dollarAmount)
{
return $(dollarAmount).replace('$','');
}
如果您不是在处理金钱问题,并且有不同的十进制格式要求,这里有一个更通用的函数:
function addCommas(number, minDecimalPlaces = 0, maxDecimalPlaces = Math.max(3,minDecimalPlaces))
{
const options = {};
options.maximumFractionDigits = maxDecimalPlaces;
options.minimumFractionDigits = minDecimalPlaces;
return Intl.NumberFormat('en-US',options).format(number);
}
哦,顺便说一句,这段代码在某些旧版本的Internet Explorer中不起作用完全是故意的。我试图随时打破IE,因为它不支持现代标准。
请记住,在评论部分过分的赞扬被认为是离题的。相反,你只要给我一大堆选票。