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

我是这样做的:

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

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


当前回答

仅适用于未来的谷歌人(或不一定是“谷歌人”):

上面提到的所有解决方案都很好,然而,RegExp在这种情况下使用可能是非常糟糕的。

因此,是的,您可以使用一些建议的选项,甚至编写一些原始但有用的东西,如:

const strToNum = str => {

   //Find 1-3 digits followed by exactly 3 digits & a comma or end of string
   let regx = /(\d{1,3})(\d{3}(?:,|$))/;
   let currStr;

   do {
       currStr = (currStr || str.split(`.`)[0])
           .replace( regx, `$1,$2`)
   } while (currStr.match(regx)) //Stop when there's no match & null's returned

   return ( str.split(`.`)[1] ) ?
           currStr.concat(`.`, str.split(`.`)[1]) :
           currStr;

};

strToNum(`123`) // => 123
strToNum(`123456`) // => 123,456
strToNum(`-1234567.0987`) // => -1,234,567.0987

这里使用的正则表达式相当简单,循环将精确到完成任务所需的次数。

你可能会优化得更好,“DRYify”代码等等。

然而

(-1234567.0987).toLocaleString();

(在大多数情况下)将是更好的选择。

重点不在于执行速度或跨浏览器兼容性。

在您想向用户显示结果数字的情况下,.toLocaleString()方法可以让您与网站或应用程序的用户使用相同的语言(无论她/他的语言是什么)。

根据ECMAScript文档,这种方法于1999年引入,我认为其原因是希望互联网在某个时刻将连接世界各地的人们,因此需要一些“内部化”工具。

今天,互联网确实连接了我们所有人,因此,重要的是要记住,世界比我们想象的更复杂&我们(几乎)都在互联网中。

显然,考虑到人的多样性,不可能保证每个人都有完美的用户体验,因为我们讲不同的语言,看重不同的东西,等等。正因为如此,尽可能地将事情本地化更为重要。

因此,考虑到日期、时间、数字等的表示有一些特定的标准,并且我们有一个工具可以以最终用户首选的格式显示这些内容,不使用该工具是不是很少见,而且几乎是不负责任的(尤其是在我们想向用户显示这些数据的情况下)?

对我来说,在这种情况下使用RegExp而不是.toLocaleString()听起来有点像用JavaScript创建一个时钟应用程序,并以这种方式对其进行硬编码,这样它将只显示布拉格时间(这对于不住在布拉格的人来说非常无用),尽管默认行为是

new Date();

是根据最终用户的时钟返回数据。

其他回答

让我试着改进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()。

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

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

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/

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

// 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。

您可以在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