我试图在JavaScript中打印一个整数,用逗号作为千位分隔符。例如,我想将数字1234567显示为“1234567”。我该怎么做?
我是这样做的:
函数编号WithCommas(x){x=x.toString();var模式=/(-?\d+)(\d{3})/;while(模式测试(x))x=x.replace(模式,“$1,$2”);返回x;}console.log(数字与逗号(1000))
有没有更简单或更优雅的方法?如果它也可以与浮点运算一起使用,那就很好了,但这不是必须的。它不需要特定于区域设置来决定句点和逗号。
@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位数的倍数时发生(未来光标到达原点末端的情况)。
如果您正在处理货币值和格式设置,那么添加处理大量边缘情况和本地化的微小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
您可以使用此过程格式化所需货币。
var nf = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
nf.format(123456.789); // ‘$123,456.79’
有关详细信息,您可以访问此链接。
https://www.justinmccandless.com/post/formatting-currency-in-javascript/
已经有很多好答案了。这里还有一个,只是为了好玩:
function format(num, fix) {
var p = num.toFixed(fix).split(".");
return p[0].split("").reduceRight(function(acc, num, i, orig) {
if ("-" === num && 0 === i) {
return num + acc;
}
var pos = orig.length - i - 1
return num + (pos && !(pos % 3) ? "," : "") + acc;
}, "") + (p[1] ? "." + p[1] : "");
}
一些示例:
format(77.03453, 2); // "77.03"
format(78436589374); // "78,436,589,374"
format(784, 4); // "784.0000"
format(-123456); // "-123,456"
下面是两个不同的浏览器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