我想在 JavaScript 中使用逗号作为千位分隔符打印整数。例如,我想将数字 1234567 显示为“1,234,567”。我该如何做到这一点?
我是这样做的:
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
console.log(numberWithCommas(1000))
有没有更简单或更优雅的方法来做到这一点?如果它也可以处理浮点数,那就太好了,但这并不是必需的。它不需要是特定于区域设置的,以决定使用句点还是逗号。
Number.prototype.toLocaleString
在Safari浏览器中仍然不起作用。它只是返回数字本身,而没有错误抛出。由于这个问题,今天我感到非常无语... #goodworkApple - aendra