我试图在JavaScript中打印一个整数,用逗号作为千位分隔符。例如,我想将数字1234567显示为“1234567”。我该怎么做?
我是这样做的:
函数编号WithCommas(x){x=x.toString();var模式=/(-?\d+)(\d{3})/;while(模式测试(x))x=x.replace(模式,“$1,$2”);返回x;}console.log(数字与逗号(1000))
有没有更简单或更优雅的方法?如果它也可以与浮点运算一起使用,那就很好了,但这不是必须的。它不需要特定于区域设置来决定句点和逗号。
如果您正在处理货币值和格式设置,那么添加处理大量边缘情况和本地化的微小accounting.js可能是值得的:
// Default usage:
accounting.formatMoney(12345678); // $12,345,678.00
// European formatting (custom symbol and separators), could also use options object as second param:
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
// Negative values are formatted nicely, too:
accounting.formatMoney(-500000, "£ ", 0); // £ -500,000
// Simple `format` string allows control of symbol position [%v = value, %s = symbol]:
accounting.formatMoney(5318008, { symbol: "GBP", format: "%v %s" }); // 5,318,008.00 GBP
我想我应该分享一个小技巧,我正在使用它来格式化大数字。我没有插入逗号或空格,而是在“千”之间插入一个空的但可见的跨度。这使得数千个输入很容易看到,但它允许以原始格式复制/粘贴输入,不使用逗号/空格。
// 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。
可以使用浏览器的Intl对象以国际友好的方式插入千位分隔符:
Intl.NumberFormat().format(1234);
// returns "1,234" if the user's locale is en_US, for example
有关详细信息,请参阅MDN关于NumberFormat的文章,您可以指定区域设置行为或用户的默认设置。这是一个更加简单的方法,因为它尊重当地的差异;许多国家使用句点分隔数字,而逗号表示小数。
Intl.NumberFormat尚未在所有浏览器中都可用,但它在最新的Chrome、Opera和IE中都可以使用。Firefox的下一版本应该支持它。Webkit似乎没有实现时间表。