我试图在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
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”
欢呼
我在早些时候找到了这个答案,我更新了它以允许负数。
您可以在将数字转换为字符串后使用它。
删除额外的小数位数只是为了方便,因为这是一种非常常见的情况。如果不需要,可以跳过它。
// Keep only digits, hyphen and decimal points:
myNum.toString() .replace(/[^-\d.]/g, "")
// Remove duplicated decimal point, if one exists:
.replace(/^(\d*\.)(.*)\.(.*)$/, '$1$2$3')
// Keep only two digits past the decimal point:
.replace(/\.(\d{2})\d+/, '.$1')
// Add thousands separators:
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")