Vanilla JavaScript Number toLocaleString

β€” 3 minute read


Yesterday we saw how to get a month's name using the toLocalString function.

This made me wonder what else it could be used for, and as it turns out, we can use it for Numbers as well!

So in today's tutorial we will learn how to use the toLocaleString method on numbers and currencies.

JavaScript Number toLocaleString function permalink

The syntax for this method is the same as we saw yesterday when converting a date object.

number.toLocaleString('locale', {options});

In the most default way, we don't have to pass any arguments, and we will get the browser's default.

var number = 123456.789;

// 123,456.789

Number toLocaleString for different countries permalink

To use different locales for country and language codes we can pass along the locale parameters as follows:

// 123.456,789
// 123,456.789
// 1,23,456.789

Number.toLocaleString for currencies permalink

The toLocaleString method has a lot of available options. Let's say we want to convert a number to a local currency format.

By passing a style of currency with a currency name, we can convert the number in e.g. EUR, USD or INR.

console.log(number.toLocaleString('nl-NL', {style: 'currency', currency: 'EUR'}));
// € 123.456,79
console.log(number.toLocaleString('en-US', {style: 'currency', currency: 'USD'}));
// $123,456.79
console.log(number.toLocaleString('en-IN', {style: 'currency', currency: 'INR'}));
// β‚Ή1,23,456.79

Awesome right?

Other Options permalink

Other style options we can use with the method are:

View the code examples in this Codepen permalink

See the Pen Vanilla JavaScript Number toLocaleString by Chris Bongers (@rebelchris) on CodePen.

Browser Support permalink

This JavaScript method is a widely supported method. Feel free to use it.

toLocaleString browser support

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter