我试图在JavaScript中打印一个整数,用逗号作为千位分隔符。例如,我想将数字1234567显示为“1234567”。我该怎么做?
我是这样做的:
函数编号WithCommas(x){x=x.toString();var模式=/(-?\d+)(\d{3})/;while(模式测试(x))x=x.replace(模式,“$1,$2”);返回x;}console.log(数字与逗号(1000))
有没有更简单或更优雅的方法?如果它也可以与浮点运算一起使用,那就很好了,但这不是必须的。它不需要特定于区域设置来决定句点和逗号。
这里有一个简单的函数,它为千个分隔符插入逗号。它使用数组函数而不是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
我找到了一种适用于所有情况的方法。CodeSandbox示例
function commas(n) {
if (n < 1000) {
return n + ''
} else {
// Convert to string.
n += ''
// Skip scientific notation.
if (n.indexOf('e') !== -1) {
return n
}
// Support fractions.
let i = n.indexOf('.')
let f = i == -1 ? '' : n.slice(i)
if (f) n = n.slice(0, i)
// Add commas.
i = n.length
n = n.split('')
while (i > 3) n.splice((i -= 3), 0, ',')
return n.join('') + f
}
}
这就像诺亚·弗雷塔斯(Noah Freitas)的答案,但支持分数和科学记数法。
我认为如果性能不受关注,toLocaleString是最好的选择。
edit:这里有一个CodeSandbox,其中包含一些示例:https://codesandbox.io/s/zmvxjpj6x
我在早些时候找到了这个答案,我更新了它以允许负数。
您可以在将数字转换为字符串后使用它。
删除额外的小数位数只是为了方便,因为这是一种非常常见的情况。如果不需要,可以跳过它。
// 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, ",")
您可以在Number原型上创建一个函数
Number.prototype.format = function (s, d) {
return (
this.toString()
.split(".")
.map((n, i) =>
i
? n
: n
.split("")
.map((n, i) => (i % 3 || !i ? n : s + n))
.join("")
)
.join(d)
);
};
console.log((8800.00).format(',', '.'))
// 8,880.00
// French notation
console.log((8800.00).format(' ', ','))
// 8 880,00