DEV Community

Cover image for Vanilla JavaScript Number toLocaleString

Vanilla JavaScript Number toLocaleString

Chris Bongers
I write daily web development tips that help you become a more efficient developer. 👨‍💻⚡️
Originally published at ・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!

JavaScript Number toLocaleString function

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

number.toLocaleString('locale', {options});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Number.toLocaleString locales

To use different locales we can pass along the locale parameters as such:

// 123.456,789
// 123,456.789
// 1,23,456.789
Enter fullscreen mode Exit fullscreen mode

Number.toLocaleString options

This method has a lot of available options, let's say we want to convert to a local currency format.

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
Enter fullscreen mode Exit fullscreen mode

Awesome right!

Other styles we can use are:

View this method on Codepen.

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

Browser Support

This is a widely supported method, feel free to use it.

View on CanIUse

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

Discussion (0)