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

我是这样做的:

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

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


当前回答

我找到了一种适用于所有情况的方法。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

其他回答

我认为该功能将处理与此问题相关的所有问题。

function commaFormat(inputString) {
    inputString = inputString.toString();
    var decimalPart = "";
    if (inputString.indexOf('.') != -1) {
        //alert("decimal number");
        inputString = inputString.split(".");
        decimalPart = "." + inputString[1];
        inputString = inputString[0];
        //alert(inputString);
        //alert(decimalPart);

    }
    var outputString = "";
    var count = 0;
    for (var i = inputString.length - 1; i >= 0 && inputString.charAt(i) != '-'; i--) {
        //alert("inside for" + inputString.charAt(i) + "and count=" + count + " and outputString=" + outputString);
        if (count == 3) {
            outputString += ",";
            count = 0;
        }
        outputString += inputString.charAt(i);
        count++;
    }
    if (inputString.charAt(0) == '-') {
        outputString += "-";
    }
    //alert(outputString);
    //alert(outputString.split("").reverse().join(""));
    return outputString.split("").reverse().join("") + decimalPart;
}

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

我在Aki143S的解决方案中添加了tofixed。此解决方案使用点表示千位分隔符,使用逗号表示精度。

function formatNumber( num, fixed ) { 
    var decimalPart;

    var array = Math.floor(num).toString().split('');
    var index = -3; 
    while ( array.length + index > 0 ) { 
        array.splice( index, 0, '.' );              
        index -= 4;
    }

    if(fixed > 0){
        decimalPart = num.toFixed(fixed).split(".")[1];
        return array.join('') + "," + decimalPart; 
    }
    return array.join(''); 
};

示例;

formatNumber(17347, 0)  = 17.347
formatNumber(17347, 3)  = 17.347,000
formatNumber(1234563.4545, 3)  = 1.234.563,454

我的“真正”正则表达式唯一的解决方案

你看到上面那些热情的球员了吗?也许你可以打高尔夫球,这是我的击球。

n => `${n}`.replace(/(?<!\.\d+)\B(?=(\d{3})+\b)/g, " ").replace(/(?<=\.(\d{3})+)\B/g, " ")

使用 如国际单位制在其出版物《国际单位制手册:国际单位制(SI)》(见§5.3.4.)第八版(2006年)中所说,千位分隔符的空格(U+2009)。第九版(2019年)建议使用空格(见§5.4.4.)。你可以使用任何你想要的东西,包括逗号。


See.

const integer_part_only=n=>`${n}`.replace(/(?<!\.\d+)\B(?=(\d{3})+\B)/g,“I”);const fractional_part_only=n=>`${n}`替换(/(?<=\.(\d{3})+)\B/g,“F”);const both=n=>仅分数部分(整数部分(n));功能演示(编号){//我正在使用Chrome 74。console.log(`${number}→ “${integer_part_only(number)}”(仅整数部分)→ “${fractional_part_only(数字)}”(仅分数部分)→ “${both(number)}”(both)`);}演示(Math.random()*10e5);演示(123456789.01234567);演示(123456789);演示(0.0123456789);


它是如何工作的?

对于整数部分

.replace(/(?<!\.\d+)\B(?=(\d{3})+\b)/g, " I ")

.替换(……,“I”)放入“I”/……/克\B两个相邻数字之间(?=……)右侧部分为(\d{3})+一个或多个三位数块\b后跟非数字,例如句点、字符串结尾等,(?<!……)负外观,不包括其左侧部分\.\d+是一个后跟数字的点(“有一个小数分隔符”)。

对于小数部分

.replace(/(?<=\.(\d{3})+)\B/g, " F ")

.替换(……,“F”)放入“F”/……/克\B两个相邻数字之间(?<=……)左半部分为\. 十进制分隔符(\d{3})+后跟一个或多个三位数块。


字符类和边界

\d)匹配任何数字(阿拉伯数字)。相当于[0-9]。例如/\d/或/[0-9]/匹配B2中的2是组号。\b级匹配单词边界。这是一个单词字符后面或前面没有其他单词字符的位置,例如在字母和空格之间。注意,匹配中不包括匹配的单词边界。换句话说,匹配单词边界的长度为零。示例:/\bm/匹配月亮中的m;/oo\b/与moon中的oo不匹配,因为oo后面跟着n,n是一个单词字符;/oon \b/匹配moon中的oon,因为oon是字符串的结尾,因此后面不跟单词字符;/\w\b/w/将永远不会匹配任何内容,因为单词字符后面永远不能同时跟有非单词和单词字符。\B级匹配非单词边界。这是上一个字符和下一个字符类型相同的位置:要么两者都必须是单词,要么两者都是非单词。例如两个字母之间或两个空格之间。字符串的开头和结尾被视为非单词。与匹配的单词边界相同,匹配的非单词边界也不包括在匹配中。例如/\中午开始比赛;/你昨天可能和你比赛。


浏览器兼容性

https://caniuse.com/#feat=js-正则表达式查找

以下代码使用字符扫描,因此没有正则表达式。

function commafy( num){
  var parts = (''+(num<0?-num:num)).split("."), s=parts[0], L, i=L= s.length, o='';
  while(i--){ o = (i===0?'':((L-i)%3?'':',')) 
                  +s.charAt(i) +o }
  return (num<0?'-':'') + o + (parts[1] ? '.' + parts[1] : ''); 
}

它显示出令人期待的性能:http://jsperf.com/number-formatting-with-commas/5

2015.4.26:在num<0时解决问题的小修复。看见https://jsfiddle.net/runsun/p5tqqvs3/