我试图在JavaScript中打印一个整数,用逗号作为千位分隔符。例如,我想将数字1234567显示为“1234567”。我该怎么做?

我是这样做的:

函数编号WithCommas(x){x=x.toString();var模式=/(-?\d+)(\d{3})/;while(模式测试(x))x=x.replace(模式,“$1,$2”);返回x;}console.log(数字与逗号(1000))

有没有更简单或更优雅的方法?如果它也可以与浮点运算一起使用,那就很好了,但这不是必须的。它不需要特定于区域设置来决定句点和逗号。


当前回答

我对这个问题的答案数量印象深刻。我喜欢uKolka的回答:

n.toLocaleString()

但不幸的是,在西班牙语等一些地区,它并不能像预期的那样工作(IMHO):

Number(1000).toLocaleString('ES-es')

给出1000而不是1.000。

请参阅所有浏览器中不能处理小于10000的数字的LocaleString,了解原因。

因此,我不得不使用Elias Zamaria选择正确的千位分隔符的答案:

n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, Number(10000).toLocaleString().substring(2, 3))

对于使用或的两个语言环境,这一行程序都可以很好地作为一行程序使用。在所有情况下,从1000开始工作。

Number(1000).toString().replace(/\B(?=(\d{3})+(?!\d))/g, Number(10000).toLocaleString().substring(2, 3))

给出1.000的西班牙语区域设置上下文。

如果您想对数字的格式进行绝对控制,也可以尝试以下操作:

let number   = 1234.567
let decimals = 2
let decpoint = '.' // Or Number(0.1).toLocaleString().substring(1, 2)
let thousand = ',' // Or Number(10000).toLocaleString().substring(2, 3)

let n = Math.abs(number).toFixed(decimals).split('.')
n[0] = n[0].split('').reverse().map((c, i, a) =>
  i > 0 && i < a.length && i % 3 == 0 ? c + thousand : c
).reverse().join('')
let final = (Math.sign(number) < 0 ? '-' : '') + n.join(decpoint)

console.log(final)

给出1234.57。

这个不需要正则表达式。它的工作原理是先用toFixed将数字调整到所需的小数位数,然后将其除以小数点。如果有的话。然后将左侧转换为一个数字数组,该数组被反转。然后,从开头开始每三位数字添加一个千位分隔符,结果再次反转。最终的结果是两部分的结合。首先用Math.abs去掉输入数字的符号,必要时再放回去。

它不是一个线性函数,但长度不长,很容易转化为函数。为了清楚起见,添加了变量,但如果事先知道,可以用它们的期望值替换这些变量。您可以使用使用toLocaleString的表达式来查找当前区域设置的小数点和千位分隔符的正确字符(请记住,这些字符需要更现代的Javascript)

其他回答

在这里没有找到一个现代和全面的解决方案之后,我编写了一个箭头函数(没有正则表达式)来解决格式化问题,它允许调用者为欧洲和世界其他地区提供小数位数以及句点和千位分隔符。

示例:数字格式化程序(1234567890.123456)=>1234567890数字格式化程序(1234567890.123456,4)=>1234567890.1235numberFormatter(1234567890.123456,4,'.',',')=>1.234.567.8901235欧洲

以下是用ES6(现代语法)编写的函数:

const numberFormatter = (number, fractionDigits = 0, thousandSeperator = ',', fractionSeperator = '.') => {
    if (number!==0 && !number || !Number.isFinite(number)) return number
    const frDigits = Number.isFinite(fractionDigits)? Math.min(Math.max(fractionDigits, 0), 7) : 0
    const num = number.toFixed(frDigits).toString()

    const parts = num.split('.')
    let digits = parts[0].split('').reverse()
    let sign = ''
    if (num < 0) {sign = digits.pop()}
    let final = []
    let pos = 0

    while (digits.length > 1) {
        final.push(digits.shift())
        pos++
        if (pos % 3 === 0) {final.push(thousandSeperator)}
    }
    final.push(digits.shift())
    return `${sign}${final.reverse().join('')}${frDigits > 0 ? fractionSeperator : ''}${frDigits > 0 && parts[1] ? parts[1] : ''}`
}

它已被测试为阴性、不良输入和NaN病例。如果输入是NaN,则只需返回它。

如果您正在处理货币值和格式设置,那么添加处理大量边缘情况和本地化的微小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

我在早些时候找到了这个答案,我更新了它以允许负数。

您可以在将数字转换为字符串后使用它。

删除额外的小数位数只是为了方便,因为这是一种非常常见的情况。如果不需要,可以跳过它。

// 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, ",")

这是@mikez302答案的变体,但修改为支持带小数的数字(根据@neu-rah的反馈,numberWithCommas(12345.6789)->“12345.6789”而不是“12345.6788”

function numberWithCommas(n) {
    var parts=n.toString().split(".");
    return parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}

这里有一个简单的函数,它为千个分隔符插入逗号。它使用数组函数而不是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