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

我是这样做的:

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

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


当前回答

已经有很多好答案了。这里还有一个,只是为了好玩:

function format(num, fix) {
    var p = num.toFixed(fix).split(".");
    return p[0].split("").reduceRight(function(acc, num, i, orig) {
        if ("-" === num && 0 === i) {
            return num + acc;
        }
        var pos = orig.length - i - 1
        return  num + (pos && !(pos % 3) ? "," : "") + acc;
    }, "") + (p[1] ? "." + p[1] : "");
}

一些示例:

format(77.03453, 2); // "77.03"
format(78436589374); // "78,436,589,374"
format(784, 4);      // "784.0000"
format(-123456);     // "-123,456"

其他回答

与@elias zamaria和@t.j.crowder相关

Safari浏览器的负面外观是不能使用<。所以,应该是(?!\.\d*)

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

它适用于Safari和Firefox

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

可以使用浏览器的Intl对象以国际友好的方式插入千位分隔符:

Intl.NumberFormat().format(1234);
// returns "1,234" if the user's locale is en_US, for example

有关详细信息,请参阅MDN关于NumberFormat的文章,您可以指定区域设置行为或用户的默认设置。这是一个更加简单的方法,因为它尊重当地的差异;许多国家使用句点分隔数字,而逗号表示小数。

Intl.NumberFormat尚未在所有浏览器中都可用,但它在最新的Chrome、Opera和IE中都可以使用。Firefox的下一版本应该支持它。Webkit似乎没有实现时间表。

这是一个编码更少的好解决方案。。。

var y = "";
var arr = x.toString().split("");
for(var i=0; i<arr.length; i++)
{
    y += arr[i];
    if((arr.length-i-1)%3==0 && i<arr.length-1) y += ",";
}

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