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

我是这样做的:

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

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


当前回答

这是我的尝试:

编辑:以小数形式添加

函数splitMille(n,分隔符=','){//转换为字符串设num=(n+“”)//测试并获取任何小数(后面的操作不支持它们)让小数=“”if(/\./.test(num)){//此正则表达式获取小数点和小数小数=num.replace(/^.*(\..*)$/,“$1”)}//从数字字符串中删除小数num=num.replace(小数,“”)//通过Array函数反转数字字符串.split(“”).reverse().join(“”//分成1-3个字符的组(负数可选支持字符“-”).match(/[0-9]{1,3}-?/g)//添加mille分隔符并反转.join(分隔符).split(“”).reverse().join//将小数返回并输出格式化的数字返回`${num}${decimals}`}让testA=splitMille(1234)让testB=splitMille(-1234)让testC=splitMille(123456.789)让testD=splitMille(9007199254740991)let testE=splitMille(1000.0001)console.log('结果!\n\tA:%s\n\tB:%s\n\tC:%s\n\tD:%s\n\t E:%s',testA,testB,testC,testD,testE)

其他回答

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

示例:数字格式化程序(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,则只需返回它。

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

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

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

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

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

您可以使用此过程格式化所需货币。

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/

@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位数的倍数时发生(未来光标到达原点末端的情况)。