我试图在JavaScript中打印一个整数,用逗号作为千位分隔符。例如,我想将数字1234567显示为“1234567”。我该怎么做?
我是这样做的:
函数编号WithCommas(x){x=x.toString();var模式=/(-?\d+)(\d{3})/;while(模式测试(x))x=x.replace(模式,“$1,$2”);返回x;}console.log(数字与逗号(1000))
有没有更简单或更优雅的方法?如果它也可以与浮点运算一起使用,那就很好了,但这不是必须的。它不需要特定于区域设置来决定句点和逗号。
下面是两个不同的浏览器API,它们可以将数字转换为结构化字符串。请记住,并非所有用户的计算机都具有在数字中使用逗号的区域设置。要在输出中强制使用逗号,可以使用任何“西部”语言环境,例如en-US
let number = 1234567890; // Example number to be converted
⚠️ 注意javascript的最大整数值为9007199254740991
到LocaleString
// default behaviour on a machine with a local that uses commas for numbers
let number = 1234567890;
number.toLocaleString(); // "1,234,567,890"
// With custom settings, forcing a "US" locale to guarantee commas in output
let number2 = 1234.56789; // floating point example
number2.toLocaleString('en-US', {maximumFractionDigits:2}); // "1,234.57"
//You can also force a minimum of 2 trailing digits
let number3 = 1.5;
number3.toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2}); //"1.50"
数字格式
let number = 1234567890;
let nf = new Intl.NumberFormat('en-US');
nf.format(number); // "1,234,567,890"
根据我的检查(至少是Firefox),它们在性能方面或多或少都是相同的。
⚡ 现场演示:https://codepen.io/vsync/pen/MWjdbgL?editors=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。
@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位数的倍数时发生(未来光标到达原点末端的情况)。
这里有一个简单的函数,它为千个分隔符插入逗号。它使用数组函数而不是RegEx。
/**
* Format a number as a string with commas separating the thousands.
* @param num - The number to be formatted (e.g. 10000)
* @return A string representing the formatted number (e.g. "10,000")
*/
var formatNumber = function(num) {
var array = num.toString().split('');
var index = -3;
while (array.length + index > 0) {
array.splice(index, 0, ',');
// Decrement by 4 since we just added another unit to the array.
index -= 4;
}
return array.join('');
};
CodeSandbox链接,示例如下:https://codesandbox.io/s/p38k63w0vq