如何在不引入i18n的情况下让节点以数字字符串输出逗号? [英] can I get node to output commas in number strings without bringing in i18n?

查看:166
本文介绍了如何在不引入i18n的情况下让节点以数字字符串输出逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

并不是说添加一个需求很重要,但是节点文档建议您不需要它:

Not that adding a require is a big deal but the 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",并且输出未更改.

Do I have to bring in i18n to get commas in my numbers? There's nothing about that on the nodejs docs for Number.toLocaleString. My LANG looks correct, as far as I know, which isn't far. Tried setting process.env.LANG to 'en-US' and the output didn't change.

推荐答案

(等待几天才能获得其他答案)

(waited a few days for other answers)

看起来这是一个已知问题,我发现的文档不是官方的.我找不到有关此行为的任何官方文档. MDN文档假定存在浏览器(该浏览器为i18n).浏览器外部的V8记录不良.

Looks like this is a known issue and the docs that I found are not official. I was unable to find any official docs of this behavior. MDN docs assume a browser is present (which would have i18n). V8 outside of the browser is poorly documented.

https://github.com/joyent/node/issues/4689

bnoordhuis评论:

bnoordhuis commented:

这可以说是V8错误.它忽略语言环境设置.实际上,所有日期和数字格式逻辑都是硬编码的.

This is arguably a V8 bug. It ignores locale settings. In fact, all date and number formatting logic is hard-coded.

它在Chrome和Chromium中运行的原因是那些项目在V8之上使用v8-i18n.我认为这不是我们要采取的方向.这取决于libicu,这是一个庞大的库.我们将不得不捆绑它,这将使我们已经很大的源代码树再增加85 MB和大约500,000个LoC.

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.

我的解决方法是(咖啡):

My solution was this (coffee):

Number::withCommas = ->
  parts = this.toString().split(".")
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")
  parts.join "."

替代解决方案:使用 numeral.js .这很漂亮.

Alternate solution: Use numeral.js. It's nifty.

这篇关于如何在不引入i18n的情况下让节点以数字字符串输出逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆