This is a quick tip post, but there’s a tonne of "cool" syntax features in ES6, but when you dig around a little more you’ll find a few nicities knocking around (which I tend to find by playing in devtools' console).

[I’ve published 38 videos for new developers, designers, UX, UI, product owners and anyone who needs to conquer the command line today.](https://training.leftlogic.com/buy/terminal/cli2?coupon=BLOG\&utm_source=blog\&utm_medium=banner\&utm_campaign=remysharp-discount)

I was recently working on a node based project which needed to format a number from 1600.6666 to £1,600.67. Initially I went spelunking for a npm package that did the job for me. I found [format.js](http://formatjs.io/) and [numeral.js](http://numeraljs.com/)…and quite a number of other options.

But why add another library to my code, when I can use ES6?

toLocaleString(…)[](#tolocalestring)

Enter toLocaleString with powerups! Firstly, the function is available on a few prototype chains, including String and Number. We want the the Number (i.e. "1000".toLocaleString() doesn’t do want we want).

Let’s take a look (or play with [this bin](https://jsbin.com/pihahih/1/edit)):

// => 1,600.667
(1600.666666).toLocaleString();

// => 1.600,667
(1600.666666).toLocaleString('de-DE');

// => 1,600.67
(1600.666666).toLocaleString('gb-GB', {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});

// => 1,600.00
(1600).toLocaleString('gb-GB', {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});

So now instead of messing around with Math.round or .toFixed, if I have support for toLocaleString, then I’ll use it for perfect formating.

Published 13-Dec 2016 under #web. [Edit this post](https://github.com/remy/remysharp.com/blob/main/public/blog/format-numjsor-es6.md)

Comments

Lock Thread

Login

Add Comment[M ↓   Markdown]()

[Upvotes]()[Newest]()[Oldest]()

![](/images/no-user.svg)

Axel Rauschmayer

0 points

7 years ago

Technically, this belongs more to the ECMAScript Internationalization API (ECMA-402) than to ES6: [http://www.ecma-internation…​;](http://www.ecma-international.org/ecma-262/6.0/#sec-number.prototype.tolocalestring)

![](/images/no-user.svg)

Paul Crump

0 points

7 years ago

Why not use math terminology? Like minimumDecimalPlaces, maximumDecimalPlaces, and the same for sigificant figures.

![](/images/no-user.svg)

rem

0 points

7 years ago

I think you need to ask the Ecmascript committee, rather than me…

![](/images/no-user.svg)

WebReflection

0 points

7 years ago

Probably worth mentioning you can use navigator.language by default.

const localNum = (num) => num.toLocaleString(
  navigator.language,
  {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }
);

![](/images/no-user.svg)

Šime Vidas

0 points

7 years ago

[Commento](https://commento.io)