Format Numbers with Commas in JavaScript
Table of Contents
In most cases, you will want to format numbers in JavaScript with commas, especially when the numbers are large.
Reading large numbers is a lot easier when there are commas in them.
In this post, we'll learn how to format numbers in JavaScript with commas.
toLocaleString()
The best way to format numbers in JavaScript is to use the toLocaleString()
method. This method exists on the Number
object and will return a string with the number formatted with commas.
If you live in the US, you can pass the method a locale string of en-US
to format the number with commas.
Let's look at how to format a number with commas in JavaScript:
JAVASCRIPTconst number = 123456789;
const formattedNumber = number.toLocaleString("en-US");
console.log(formattedNumber); // 1,234,567,890
It even works for floating point numbers:
JAVASCRIPTconst number = 12345.6789;
const formattedNumber = number.toLocaleString("en-US");
console.log(formattedNumber); // 12,345.679
The great thing about using toLocaleString()
is that it will work for any locale. If you want to format a number with periods like in Germany, you can pass the method a locale string of de-DE
to format the number with periods.
Here's an example of that:
JAVASCRIPTconst number = 123456789;
const formattedNumber = number.toLocaleString("de-DE");
console.log(formattedNumber); // 123.456.789
How cool is that? Now you can format numbers in JavaScript with commas or periods, depending on the locale.
Conclusion
In this post, we took a look at how to format numbers in JavaScript with commas. We also looked at how to format numbers with periods, by simply passing the toLocaleString()
method a different locale string.
Hopefully, this has helped you understand how to format numbers in JavaScript.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a PHP app using Docker
- Getting Started with Deno
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Moment.js
- Getting Started with Vuex: Managing State in Vue
- How To Create a Modal Popup Box with CSS and JavaScript
- Getting Started with Moon.js