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

我是这样做的:

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

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


当前回答

function formatNumber (num) {
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}

print(formatNumber(2665));      // 2,665
print(formatNumber(102665));    // 102,665
print(formatNumber(111102665)); // 111,102,665

其他回答

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

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

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

它适用于Safari和Firefox

这是我的尝试:

编辑:以小数形式添加

函数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)

使用此代码处理印度的货币格式。可以更改国家/地区代码以处理其他国家/地区货币。

let amount =350256.95
var formatter = new Intl.NumberFormat('en-IN', {
  minimumFractionDigits: 2,
});

// Use it.

formatter.format(amount);

输出:

3,50,256.95

Intl.NumberFormat(国际数字格式)

本机JS函数。支持IE11、Edge、最新Safari、Chrome、Firefox、Opera、iOS上的Safari和Android上的Chrome。

var number = 3500;

console.log(new Intl.NumberFormat().format(number));
// → '3,500' if in US English locale

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