Vanilla JavaScript Number toLocaleString

✍️

Today we are exploring the JavaScript Number toLocaleString method by converting numbers into local currencies. See the example in Codepen!

23 May, 2020 · 2 min 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

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

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

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

const number = 123456.789;

console.log(number.toLocaleString());
// 123,456.789

Number toLocaleString for different countries

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

console.log(number.toLocaleString('nl-NL'));
// 123.456,789
console.log(number.toLocaleString('en-US'));
// 123,456.789
console.log(number.toLocaleString('en-IN'));
// 1,23,456.789

Number.toLocaleString for currencies

The toLocaleString method has a lot of available options. 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

Other style options we can use with the method are:

View the code examples in this Codepen

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

Browser Support

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

toLocaleString browser support

Thank you for reading, and let's connect!

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

JavaScript sending data between windows

9 Sep, 2022 · 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 · 8 min read

Using the native payment request JavaScript API