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

我是这样做的:

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

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


当前回答

如果所有浏览器(Safari)都提供Number.protype.toLocaleString(),那么它将非常棒。

我检查了所有其他答案,但似乎没有人多填它。这里有一个poc,实际上是前两个答案的组合;如果toLocaleString工作,它会使用它,如果不工作,则使用自定义函数。

var putThousandsSeparators;putThousandsSeparators=函数(值,sep){如果(sep==null){sep=',';}//检查是否需要格式化if(value.toString()==value.toLocaleString()){//分裂小数var parts=value.toString().split('.')//格式化整数parts[0]=parts[0]。替换(/\B(?=(\d{3})+(?!\d))/g,sep);//把它们放回一起值=部件[1]?parts.join('.'):parts[0];}其他{value=value.toLocaleString();}返回值;};警报(putThousandsSeparators(1234567.890));

其他回答

使用正则表达式

function toCommas(value) {
    return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
console.log(toCommas(123456789)); // 123,456,789

console.log(toCommas(1234567890)); // 1,234,567,890
console.log(toCommas(1234)); // 1,234

使用toLocaleString()

var number = 123456.789;

// request a currency format
console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
// → 123.456,79 €

// the Japanese yen doesn't use a minor unit
console.log(number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
// → ¥123,457

// limit to three significant digits
console.log(number.toLocaleString('en-IN', { maximumSignificantDigits: 3 }));
// → 1,23,000

ref MDN:Number.protype.toLocaleString()

使用国际号码格式()

var number = 123456.789;

console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// expected output: "123.456,79 €"

// the Japanese yen doesn't use a minor unit
console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
// expected output: "¥123,457"

// limit to three significant digits
console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number));

// expected output: "1,23,000"

参考Intl.NumberFormat

在这里演示<script type=“text/javascript”>//使用正则表达式函数到逗号(值){return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g,“,”);}函数命令(){var num1=文档.myform.number1.value;//使用正则表达式document.getElementById('result1').value=toCommas(parseInt(num1));//使用toLocaleString()document.getElementById('result2').value=parseInt(num1).toLocaleString('ja-JP'{style:'货币',货币:'日元'});//使用国际号码格式()document.getElementById('result3').value=新Intl.NumberFormat('ja-JP'{style:'货币',货币:'日元'}).格式(num1);}</script><FORM NAME=“myform”><INPUT TYPE=“text”NAME=“number1”VALUE=“123456789”><br><INPUT TYPE=“button”NAME=“button“Value=”=>“onClick=”commas()“><br>使用正则表达式<br><INPUT TYPE=“text”ID=“result1”NAME=“result1”VALUE=“”><br>使用toLocaleString()<br><INPUT TYPE=“text”ID=“result2”NAME=“result2“VALUE=”“><br>使用国际号码格式()<br><INPUT TYPE=“text”ID=“result3”NAME=“result3“VALUE=”“></FORM>表演http://jsben.ch/sifRd

我认为你的解决方案是我见过的最短的解决方案之一。我认为没有任何标准的JavaScript函数可以完成这类工作,所以您可能需要自己完成。

我检查了CSS3规范,看看是否可以在CSS中实现这一点,但除非您希望每个数字都有自己的<span>,否则我认为这是不可能的。

我确实在GoogleCode上发现了一个看起来很有前途的项目:灵活的js格式。我没有使用过它,但它看起来非常灵活,并且使用JsUnit进行了单元测试。开发人员也有很多关于这个主题的帖子(尽管很旧)。

请务必考虑国际用户:许多国家使用空格作为分隔符,并使用逗号将小数与数字的整数部分分开。

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

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

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-正则表达式查找

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

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

// Use it.

formatter.format(amount);

输出:

3,50,256.95

这里有一个简单的可重用函数,它返回具有指定小数位数的字符串,并允许您切换逗号的包含。

function format_number(number, num_decimals, include_comma)
{
    return number.toLocaleString('en-US', {useGrouping: include_comma, minimumFractionDigits: num_decimals, maximumFractionDigits: num_decimals});
}

用法示例:

format_number(1234.56789, 2, true); // Returns '1,234.57'
format_number(9001.42, 0, false); // Returns '9001'

如果需要进一步自定义字符串,可以在此处找到格式选项列表。