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

我是这样做的:

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

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


当前回答

使用正则表达式

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

其他回答

我认为这是最短的正则表达式:

/\B(?=(\d{3})+\b)/g

"123456".replace(/\B(?=(\d{3})+\b)/g, ",")

我查了几个数字,结果成功了。

@user1437663的解决方案很棒。

真正理解解决方案的人是准备好理解复杂的正则表达式。

一个小的改进使它更易读:

function numberWithCommas(x) {
    var parts = x.toString().split(".");
    return parts[0].replace(/\B(?=(\d{3})+(?=$))/g, ",") + (parts[1] ? "." + parts[1] : "");
}

该模式以\B开头,以避免在单词开头使用逗号。有趣的是,模式返回为空,因为\B不前进“游标”(这同样适用于$)。

O\B后面跟着一个鲜为人知的资源,但这是Perl正则表达式的一个强大功能。

            Pattern1 (? = (Pattern2) ).

神奇的是,括号(Pattern2)中的内容是一个模式,它遵循先前的模式(Pattern1),但不前进光标,也不是返回的模式的一部分。这是一种未来模式。当有人向前看但真的不走路时,这是类似的!

在这种情况下,模式2是

\d{3})+(?=$)

它表示3位数字(一次或多次),后跟字符串结尾($)

最后,Replace方法将找到的所有模式(空字符串)更改为逗号。这仅在剩余部分是3位数的倍数时发生(未来光标到达原点末端的情况)。

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

上面提到的所有解决方案都很好,然而,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();

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

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

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