Format numbers with numberWithCommas() or Number.toLocaleString()

05 March 2019   1 comment   Web development, Javascript

https://codepen.io/peterbe/pen/xBRGoN?editors=1011#0

In a highly unscientific survey of exactly 2 French native friends, I asked them what they think about formatting large numbers the "French way" versus doing it the "English way". In particular, if the rest of content/app is English, would it be jarring if the formatting of numbers was French. Both Adrian and Mathieu said they prefer displaying the number the French way even if the app/content is French.

If you have an English browser opening https://codepen.io/peterbe/pen/xBRGoN means it's going to display the two numbers the same way. But if you have a French locale in your browser it'll look like this:

French

Number.toLocaleString() is now universally supported so that's no longer a worry.

For years I was using a function like this:

/* http://stackoverflow.com/a/2901298 */
function numberWithCommas(x) {
  var parts = x.toString().split('.');
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return parts.join('.');
}

numberWithCommas(100000000);
// "100,000,000"

jsperf
and it works and is reasonably fast too but it's so tempting to not use and instead stand on the shoulder-of-browsers to supply this functionality instead. But consider the alternative:

(100000000).toLocaleString();
// "100,000,000"

The thing that's always worried me is; What will someone's reaction be if the texts are in one locale and the formatting of numbers (and dates, etc!) are in another locale?

All 2 of the people I asked say they don't mind the mixing but admit that it's weird but that ultimately they prefer "their" format.

If you're non-English browser, what do you prefer? If you're a web usability expert, please, too, drop a comment to share what you think.

Comments

Peter Bengtsson

Something to be very aware of is that if you have a universal React (server-side) app, then `toLocaleString` will obviously yield different results on the initial render compared to consecutive renders in the client. That might be really gross.

Your email will never ever be published


Related posts

Previous:
Django ORM optimization story on selecting the least possible 22 February 2019
Related by Keyword:
Format thousands in Python 01 February 2019
Fastest way to thousands-commafy large numbers in Python/PyPy 13 October 2012