How to format numbers? [duplicate]

If you want to use built-in code, you can use toLocaleString() with minimumFractionDigits.

Browser compatibility for the extended options on toLocaleString() was limited when I first wrote this answer, but the current status looks good. If you’re using Node.js, you will need to npm install the intl package.

var value = (100000).toLocaleString(
  undefined, // leave undefined to use the visitor's browser 
             // locale or a string like 'en-US' to override it.
  { minimumFractionDigits: 2 }
);
console.log(value);

Number formatting varies between cultures. Unless you’re doing string comparison on the output,1 the polite thing to do is pick undefined and let the visitor’s browser use the formatting they’re most familiar with.2

// Demonstrate selected international locales
var locales = [
  undefined,  // Your own browser
  'en-US',    // United States
  'de-DE',    // Germany
  'ru-RU',    // Russia
  'hi-IN',    // India
  'de-CH',    // Switzerland
];
var n = 100000;
var opts = { minimumFractionDigits: 2 };
for (var i = 0; i < locales.length; i++) {
  console.log(locales[i], n.toLocaleString(locales[i], opts));
}

If you are from a culture with a different format from those above, please edit this post and add your locale code.


1 Which you shouldn’t.
2 Obviously do not use this for currency with something like {style: 'currency', currency: 'JPY'} unless you have converted to the local exchange rate. You don’t want your website to tell people the price is ¥300 when it’s really $300. Sometimes real e-commerce sites make this mistake.

Leave a Comment