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

我是这样做的:

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

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


当前回答

这是我的尝试:

编辑:以小数形式添加

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

其他回答

我建议使用phpjs.org的number_format()

function number_format(number, decimals, dec_point, thousands_sep) {
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        toFixedFix = function (n, prec) {
            // Fix for IE parseFloat(0.55).toFixed(0) = 0;
            var k = Math.pow(10, prec);
            return Math.round(n * k) / k;
        },
        s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

2014年2月13日更新

人们一直在报告这并不像预期的那样奏效,所以我做了一个包含自动化测试的JSFiddle。

更新日期:2017年11月26日

这是一个稍微修改了输出的堆栈片段:

函数number_format(数字,小数,小数点,千位整){变量n=!是有限的(+数字)?0:+数字,prec=!是有限的(+小数)?0:数学abs(小数),sep=(typeof thousands_sep===“undefined”)?“,”:千分之一秒,dec=(dec_point类型==“未定义”)?“.”:dec_点,toFixedFix=函数(n,prec){//修复IE parseFloat(0.55).toFixed(0)=0;var k=数学功率(10,prec);return数学舍入(n*k)/k;},s=(prec?toFixedFix(n,prec):数学舍入(n)).toString().split('.');如果(s[0]。长度>3){s[0]=s[0]。替换(/\B(?=(?:\d{3})+(?!\d))/g,sep);}if((s[1]||'').length<prec){s[1]=s[1]| |“”;s[1]+=新数组(prec-s[1].length+1).join('0');}return s.join(十二月);}var exampleNumber=1;函数测试(预期,数字,小数,小数点,千分位){var actual=number_format(数字,小数,小数点,千位整);控制台日志('测试用例'+exampleNumber+':'+'(小数:'+(小数类型=='未定义'?'(默认)':小数)+',dec_point:“'+(dec_point类型=='未定义'?'(默认)':dec_point)+'”'+',thousands_sep:“'+(类型的thousands-sep==='未定义'?'(默认值)':thousand_sep)+'”)');console.log('=>'+(实际==预期?'通过':'失败')+',得到“'+实际+'”,预期“'+预期+'”。');示例编号++;}测试('1235',1234.56);测试('1234,56',1234.56,2,',','');测试('1234.57',1234.5678,2,'.','');测试('67,00',67,2,',','.');测试(“1000”,1000);测试(‘67.31’,67.311,2);试验(‘1000.6’,1000.55,1);测试('67.00000000',67000,5,',','.');测试('1',0.9,0);试验(‘1.20’,‘1.20‘,2);测试(‘12000’,‘1.20’,4);测试('1.200','1.2000',3);.作为控制台包装{最大高度:100%!重要的}

我在早些时候找到了这个答案,我更新了它以允许负数。

您可以在将数字转换为字符串后使用它。

删除额外的小数位数只是为了方便,因为这是一种非常常见的情况。如果不需要,可以跳过它。

// Keep only digits, hyphen  and decimal points:
             myNum.toString()   .replace(/[^-\d.]/g, "")
                // Remove duplicated decimal point, if one exists:
                .replace(/^(\d*\.)(.*)\.(.*)$/, '$1$2$3')
                // Keep only two digits past the decimal point:
                .replace(/\.(\d{2})\d+/, '.$1')
                // Add thousands separators:
                .replace(/\B(?=(\d{3})+(?!\d))/g, ",")

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

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

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

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

使用正则表达式

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

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

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

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