我试图在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。
另一种方式,支持小数、不同的分隔符和负号。
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的一些更正,别忘了对他的评论投赞成票。
var formatNumber = function (number) {
var splitNum;
number = Math.abs(number);
number = number.toFixed(2);
splitNum = number.split('.');
splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return splitNum.join(".");
}
编辑:该函数仅适用于正数。例如:
var number = -123123231232;
formatNumber(number)
输出:“123123231232”
但要回答上面的问题,toLocaleString()方法只是解决了问题。
var number = 123123231232;
number.toLocaleString()
输出:“123123231232”
欢呼