How to define thousands separator in JavaScript

In order for toLocaleString to work, the browser / JavaScript must know the user's locale and regardless of whether a particular language uses "," or "." for thousands separator. Is it possible to access this data so that we can determine what the thousands separator is?

If not, we can use such a function ...

var thousandsSeparator = (function(){ if (typeof Number.prototype.toLocaleString === 'function') { var num = 1000; var numStr = num.toLocaleString(); if (numStr.length == 5) { return numStr.substr(1, 1); } } return ","; // fall-back })(); 

... but it feels like an unnecessary hack.

+8
javascript
source share
1 answer

Digging a little further, and I found Intl.NumberFormat . I think it is more elegant ...

 var thousandsSeparator = (function(){ if (typeof Intl === 'object') { // Gets the formatting object for your locale var numFormat = new Intl.NumberFormat(); // The resolved.pattern will be something like "#,##0.###" return numFormat.resolved.pattern.substr(1,1); } return ","; })(); 

Or if you really need an ultra-laconic ...

 var thousandsSeparator = (Intl) ? (new Intl.NumberFormat()).resolved.pattern.substr(1,1) : ","; 

Compatibility Warning:

  • An Intl object may not be supported in Safari for any reason - http://caniuse.com/#feat=internationalization - even though it is part of the standard ECMAScript.
  • While an Intl object may exist in some ECMAScript browsers, the above code will only work in Chrome .
  • Unfortunately, Firefox 40 and IE 11 do not currently have resolved properties in numFormat .

An elegant cross-browser solution still exists ...

+4
source share

All Articles