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

我是这样做的:

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

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


当前回答

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

其他回答

我很惊讶没有人提到Number.prototype.toLocaleString。它是在JavaScript 1.5中实现的(于1999年引入),因此基本上所有主要浏览器都支持它。

变量n=34523453.345;console.log(n.toLocaleString());//"34,523,453.345"

通过包含Intl,它也可以在Node.js中工作

如果你想要一些不同的东西,Numeral.js可能会很有趣。

我使用了克里的答案中的想法,但简化了它,因为我只是在为我的特定目的寻找简单的东西。以下是我所拥有的:

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

函数编号WithCommas(x){return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g,“,”);}功能测试(x,预期){常量结果=带逗号的数字(x);常量pass=result==预期;console.log(`${pass?”✓“:”错误===>“}${x}=>${result}`);回传;}让失败=0;失败+=!测试(0,“0”);失败+=!测试(100,“100”);失败+=!测试(1000,“1000”);失败+=!测试(10000,“10000”);失败+=!测试(100000,“100000”);失败+=!测试(1000000,“1000000”);失败+=!测试(10000000,“10000000”);if(失败){console.log(“${failures}测试失败”);}其他{console.log(“所有测试均通过”);}.作为控制台包装{最大高度:100%!重要的}


正则表达式使用2个前瞻断言:

一个正数用于查找字符串中其后一行中具有3位数倍数的任何点,一个否定断言,以确保该点只有3位数的倍数。替换表达式在此处放置逗号。

例如,如果您传递它123456789.01,则肯定断言将匹配7左边的每个点(因为789是3位数的倍数,678是3位的倍数,567等)。否定断言检查3位数的乘数后面没有任何数字。789后面有一个句点,所以它正好是3位数字的倍数,所以在那里有一个逗号。678是3位数的倍数,但后面有一个9,所以这3位数是4位数的一部分,逗号不在那里。567也是如此。456789是6位数字,是3的倍数,所以前面是逗号。345678是3的倍数,但后面有一个9,所以没有逗号。以此类推。\B防止正则表达式在字符串的开头加逗号。

@neu-rah提到,如果小数点后有超过3位数字,则该函数会在不需要的地方添加逗号。如果这是一个问题,您可以使用此函数:

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

函数编号WithCommas(x){var parts=x.toString().split(“.”);parts[0]=parts[0]。替换(/\B(?=(\d{3})+(?!\d))/g,“,”);return parts.join(“.”);}功能测试(x,预期){常量结果=带逗号的数字(x);常量pass=result==预期;console.log(`${pass?”✓“:”错误===>“}${x}=>${result}`);回传;}让失败=0;失败+=!测试(0,“0”);失败+=!测试(0.123456,“0.123456”);失败+=!测试(100,“100”);失败+=!测试(100.123456,“100.123456”);失败+=!测试(1000,“1000”);失败+=!测试(1000-123456,“1000-123456”);失败+=!测试(10000,“10000”);失败+=!测试(10000.123456,“10000.123454”);失败+=!测试(100000,“100000”);失败+=!测试(100000.123456,“10000.123456”);失败+=!测试(1000000,“1000000”);失败+=!测试(1000000123456,“1000000123446”);失败+=!测试(10000000,“10000000”);失败+=!测试(10000000.123456,“10000000.123454”);if(失败){console.log(“${failures}测试失败”);}其他{console.log(“所有测试均通过”);}.作为控制台包装{最大高度:100%!重要的}

@t.j.crowder指出,现在JavaScript有了lookbacking(支持信息),它可以在正则表达式本身中解决:

function numberWithCommas(x) {
    return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ",");
}

函数编号WithCommas(x){return x.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g,“,”);}功能测试(x,预期){常量结果=带逗号的数字(x);常量pass=result==预期;console.log(`${pass?”✓“:”错误===>“}${x}=>${result}`);回传;}让失败=0;失败+=!测试(0,“0”);失败+=!测试(0.123456,“0.123456”);失败+=!测试(100,“100”);失败+=!测试(100.123456,“100.123456”);失败+=!测试(1000,“1000”);失败+=!测试(1000-123456,“1000-123456”);失败+=!测试(10000,“10000”);失败+=!测试(10000.123456,“10000.123454”);失败+=!测试(100000,“100000”);失败+=!测试(100000.123456,“10000.123456”);失败+=!测试(1000000,“1000000”);失败+=!测试(1000000123456,“1000000123446”);失败+=!测试(10000000,“10000000”);失败+=!测试(10000000.123456,“10000000.123454”);if(失败){console.log(“${failures}测试失败”);}其他{console.log(“所有测试均通过”);}.作为控制台包装{最大高度:100%!重要的}

(?<!\.\d*)是一个表示匹配前面不能有。后跟零个或多个数字。至少在V8中,反向查找比拆分和连接解决方案(比较)更快。

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

让我试着改进uKolka的答案,也许可以帮助其他人节省一些时间。

使用Numeral.js。

document.body.textContent=数字(1234567).格式('0,0');<script src=“//cdnjs.cloudflare.com/ajax/libs/number.js/1.4.5/number.min.js”></script>

只有在浏览器兼容性没有问题的情况下,才应该使用Number.pr原型.toLocaleString()。

我想我应该分享一个小技巧,我正在使用它来格式化大数字。我没有插入逗号或空格,而是在“千”之间插入一个空的但可见的跨度。这使得数千个输入很容易看到,但它允许以原始格式复制/粘贴输入,不使用逗号/空格。

// This function accepts an integer, and produces a piece of HTML that shows it nicely with 
// some empty space at "thousand" markers. 
// Note, these space are not spaces, if you copy paste, they will not be visible.
function valPrettyPrint(orgVal) {
  // Save after-comma text, if present
  var period = orgVal.indexOf(".");
  var frac = period >= 0 ? orgVal.substr(period) : "";
  // Work on input as an integer
  var val = "" + Math.trunc(orgVal);
  var res = "";
  while (val.length > 0) {
    res = val.substr(Math.max(0, val.length - 3), 3) + res;
    val = val.substr(0, val.length - 3);
    if (val.length > 0) {
        res = "<span class='thousandsSeparator'></span>" + res;
    }
  }
  // Add the saved after-period information
  res += frac;
  return res;
}

使用此CSS:

.thousandsSeparator {
  display : inline;
  padding-left : 4px;
}

请参见示例JSFiddle。