并不是说添加 require 有什么大不了的,而是 node docs suggest that you don't need it:
// from the docs:
var number = 3500;
console.log(number.toLocaleString()); // Displays "3,500" in English locale
除了不会发生:
$ node
> var n = 1238909880
undefined
> n.toLocaleString()
'1238909880'
> n.toLocaleString('en-US' ) // docs on node don't suggest this, but on MDN they do so...
'1238909880'
> process.env.LANG
'en_US.UTF-8'
我是否必须引入 i18n 才能在我的数字中使用逗号? Number.toLocaleString 的 nodejs 文档中没有关于此的内容。据我所知,我的 LANG
看起来是正确的,相距不远。尝试将 process.env.LANG 设置为“en-US”,但输出没有改变。
最佳答案
(等了几天其他答案)
看起来这是一个已知问题,我找到的文档不是官方文档。我找不到任何关于此行为的官方文档。 MDN 文档假设存在浏览器(应该有 i18n)。浏览器之外的 V8 文档很少。
https://github.com/joyent/node/issues/4689
bnoordhuis commented:
This is arguably a V8 bug. It ignores locale settings. In fact, all date and number formatting logic is hard-coded.
The reason it works in Chrome and Chromium is that those projects use v8-i18n on top of V8. I don't think that's a direction we want to take. It depends on libicu and that's a massive library. We would have to bundle it and that would increase our already large source tree by another 85 MB and ~500,000 LoC.
我的解决方案是这个(咖啡):
Number::withCommas = ->
parts = this.toString().split(".")
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")
parts.join "."
替代解决方案:使用 numeral.js .这很漂亮。
关于node.js - 我可以让 Node 在不引入 i18n 的情况下在数字字符串中输出逗号吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17935594/