node.js - 我可以让 Node 在不引入 i18n 的情况下在数字字符串中输出逗号吗?

标签 node.js internationalization

并不是说添加 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/

相关文章:

javascript mysql 和 Promise

javascript - 在 html 中使用 node.js

localization - 语言代码和语言环境代码的良好定义是什么?

perl - 使用 gettext 和 Locale::TextDomain 在 Perl 中进行本地化,如果 Locale::TextDomain 不可用,则进行回退

node.js - 如何返回对 slack slash 命令的立即响应和延迟响应?

node.js - 静态中间件文件何时发送到客户端,使用node.js

javascript - 为什么我的异步函数返回一个空数组?

sql-server - 1/1/1753 在 SQL Server 中有何意义?

java - 如何以塞尔维亚语、俄语和阿拉伯语显示文本 (JSF 2.0)

ios - 我真的需要为每个 UIStoryboard 语言文件添加两次相同的元素吗?