4

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

Except that doesn't happen:

$ 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'

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.

jcollum
  • 43,623
  • 55
  • 191
  • 321
  • Yeah, the official docs are [here.](http://nodejs.org/docs/latest/api/) Thanks though, totally stealing your comma regex haha. – AlbertEngelB Apr 21 '14 at 15:34

2 Answers2

4

(waited a few days for other answers)

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 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.

My solution was this (coffee):

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

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

Community
  • 1
  • 1
jcollum
  • 43,623
  • 55
  • 191
  • 321
2

This will change. Working on getting Intl on by default in node. See https://github.com/joyent/node/pull/7719

EDIT If you download node v0.12, Intl is on by default.

Steven R. Loomis
  • 4,228
  • 28
  • 39