JavaScript format number with commas is a common task to display numeric data in a more readable format. We can prepare a number for this task by using commas as thousand separators. Even though different locations and countries use distinct number formats, JavaScript offers many ways to use its built-in functions to satisfy all worldwide requirements.
Table of Contents
While working with numerical data such as currency values, statistical numbers, or other numerical information, the most obvious requirement is to add commas to separate values of thousands, millions, and higher.
Here, we’ll talk about “JavaScript format number with commas” as thousand separators in this article. How can we handle number formatting that varies by country and location and is entirely dependent on the user’s cultural context?
In order to understand all of the JS number formatting choices at once, stick with us and read through to the end of this article.
Why “JavaScript format number with commas” is Important?
Big numbers are always hard to read or understand without comma separators. The solution is to format them in a way that makes sense to humans, breaking them into manageable chunks (e.g., 1,000,000 vs. 1000000).
- Improved Readability: Formatting numbers with commas enhances our readability. To make a large number easy to read, use thousand separators.
- User Experience: Providing numbers in a familiar, well-structured format improves the overall user experience, particularly in data-driven applications like financial platforms or e-commerce sites.
- Locale-Specific Formatting: If you are developing a global application, then user-specific number formatting based on their locale is highly required.
- Data Presentation: When presenting data in reports, dashboards, or charts, formatted numbers with commas make the data more professional and easier to analyze.
- Error Reduction: Properly formatted numbers help prevent misinterpretation and errors, particularly in critical fields such as finance and statistics, where the accurate representation of figures is paramount.
No. 1: Format Number Using toLocaleString Method
The simplest way to format a number in JavaScript is to use the toLocaleString() method. It’s a part of the number prototype in JavaScript.
It returns a formatted string in the default locale and with default options.
Syntax
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)
By tweaking both locales and options parameters, we can customize the behavior of the function to specify the language whose formatting conventions should be used.
Code Example
<script>
var num = 1234567;
var commaSeperatedNumber = num.toLocaleString();
console.log(commaSeperatedNumber); // Output: 1,234,567 for en-US locale
// You can apply specific locale (e.g., en-US)
commaSeperatedNumber = num.toLocaleString('en-US');
console.log(commaSeperatedNumber); // Output: "1,234,567"
// India specific JS number format
// thousands/lakh/crore separators
commaSeperatedNumber = num.toLocaleString("en-IN");
console.log(commaSeperatedNumber); // Output: 12,34,567 for en-IN locale
// German specific JS number format
// period for thousands
// comma as decimal separator
commaSeperatedNumber = num.toLocaleString("de-DE");
console.log(commaSeperatedNumber); // Output: 1.234.567 for german locale
// MDN example
// To handle fallback
// Here ban means Balinese. If not supported then id->indonesian culture
// will be used as fallback
commaSeperatedNumber = num.toLocaleString(["ban", "id"]);
console.log(commaSeperatedNumber); // Output: 1.234.567 for indonesian locale
</script>
Output
So far we have discussed about default and country specific locale for “javascript format number with commas”. But we do not use the option parameter yet. if you need to format a number with specific currency prefixes or postfixes then you can follow the below code example:
<script>
var num = 1234567;
const options = {
style: 'currency',
currency: "USD"
};
var commaSeperatedNumber = num.toLocaleString('en-US',options);
// JavaScript Format Number with Commas
console.log(commaSeperatedNumber); // Output: $1,234,567.00 for en-US locale
</script>
See the Current currency & funds code list.
All available formatting styles are:
Decimal – Default | For plain number formatting. |
Currency | For currency formatting. |
Percent | For percent formatting. |
Unit | For unit formatting. |
No. 2: Using Intl.NumberFormat
The Intl.NumberFormat is part of the Internationalization API and provides language-sensitive number formatting. This API is easily adapted to different languages, regions, and cultures.
It’s a constructor function and always creates a new instance of a number formatter object. You can pass one or more locales and an option style to format your number, which is very similar to toLocaleString(). It’s a very useful method to format any number in your application.
<script>
var num = 1234567;
var formatter = new Intl.NumberFormat('en-US');
var commaSeperatedNumber = formatter.format(num);
console.log(commaSeperatedNumber); // Output: 1,234,567 for en-US locale
// India specific JS number format
// thousands/lakh/crore separators
formatter = new Intl.NumberFormat("en-IN");
commaSeperatedNumber = formatter.format(num);
console.log(commaSeperatedNumber); // Output: 12,34,567 for en-IN locale
// German specific JS number format
// period for thousands
// comma as decimal separator
formatter = new Intl.NumberFormat("de-DE");
commaSeperatedNumber = formatter.format(num);
console.log(commaSeperatedNumber); // Output: 1.234.567 for german locale
// MDN example
// To handle fallback
// Here ban means Balinese. If not supported then id->indonesian culture
// will be used as fallback
formatter = new Intl.NumberFormat(["ban", "id"]);
commaSeperatedNumber = formatter.format(num);
console.log(commaSeperatedNumber); // Output: 1.234.567 for id locale
</script>
An Example Formatting with Currency
<script>
var num = 1234567;
// Currency formatting in JS
// Using Intl.NumberFormat constructor
// Used to displays the currency symbol
var options1 = {
style: 'currency',
currency: "USD",
currencyDisplay: 'symbol'
};
// Used to displays the currency code
var options2 = {
style: 'currency',
currency: "USD",
currencyDisplay: 'code'
};
// Used to displays the currency name
// along with thousand separator
var options3 = {
style: 'currency',
currency: "USD",
currencyDisplay: 'name'
};
const formatter1 = new Intl.NumberFormat('en-US',options1);
const formatter2 = new Intl.NumberFormat('en-US',options2);
const formatter3 = new Intl.NumberFormat('en-US',options3);
var commaSeperatedNumber1 = formatter1.format(num);
var commaSeperatedNumber2 = formatter2.format(num);
var commaSeperatedNumber3 = formatter3.format(num);
console.log(commaSeperatedNumber1); // Output: $1,234,567.00 for en-US locale
console.log(commaSeperatedNumber2); // Output: USD 1,234,567.00 for en-US locale
console.log(commaSeperatedNumber3); // Output: 1,234,567.00 US dollars for en-US locale
</script>
Output
While using the ‘currency’ style, the currencyDisplay option allows you to specify which currency symbol you want to display. It can take one of the following three values:
- ‘symbol’: Displays the currency symbol (e.g., $, Є).
- ‘code’: Displays the currency code (e.g., USD, EUR).
- ‘name’: Displays the currency name (e.g., US dollar, euros).
Advance Number Formatting with Intl.NumberFormat
The Intl.NumberFormat compactDisplay option provides you with a cleaner way to display large numbers in a more compact and readable format. It provides different notations for representing large numbers, such as “1K” for 1000, “1M” for 1 million, and so on.
Let’s do an example to see the compactDisplay option in action:
<script>
var num1 = 1000;
var num2 = 1000000;
// Currency formatting in JS
// Using Intl.NumberFormat constructor
// Used to displays the currency symbol
var options = {
style: 'currency',
currency: "USD",
currencyDisplay: 'symbol',
notation: 'compact'
};
const formatter = new Intl.NumberFormat('en-US',options);
var commaSeperatedNumber1 = formatter.format(num1);
var commaSeperatedNumber2 = formatter.format(num2);
console.log(commaSeperatedNumber1); // Output: $1K for en-US locale
console.log(commaSeperatedNumber2); // Output: $1M for en-US locale
</script>
Output
No. 3: Format Number with Commas Using a Third-Party Library Numeral.js
If you are developing enterprise-level applications, then it’s wise to use JS 3rd-party libraries for formatting and manipulating numbers. A lot of reliable tools are now available on the market. Such as Numeral.js, Accounting.js, or Format.js. You can choose one of them.
Here we are going to discuss one popular JS library named Numeral.js. An awesome 3rd party tool for formatting numbers easily.
So let’s start using Numeral.js, a super simple JavaScript format number with commas.
// Load JS Number formatting library Numeral.js from CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
<script>
var num = 1000000;
// Format a number with thousand seperator
var commaSeperatedNumber1 = numeral(num).format("0,0");
// Format a number with thousand seperator upto 2 decimal
var commaSeperatedNumber2 = numeral(num).format("0,0.00");
// Format a number with thousand seperator upto 3 decimal pint
var commaSeperatedNumber3 = numeral(num).format("0,0.000");
console.log(commaSeperatedNumber1); // Output: 1,000,000
console.log(commaSeperatedNumber2); // Output: 1,000,000.00
console.log(commaSeperatedNumber3); // Output: 1,000,000.000
</script>
Output
Code Explanation
In this code, we first import the Numeral.js CDN into our file. Then declare a variable to hold a number. Later on, we use the numerical library format function to apply the thousand separator.
You can also define a fixed number of decimal points along with a comma separator. Here, we also experimented with comma separators with two and three decimal places for formatting our numbers.
Using Numeral.js gives you a high level of advantage over JS inbulit functions. From fixed-length number formatting to unit-specific formatting, you can achieve a lot more from this library. Check out the documentation of Numeral.js for all available formatting options.
No. 4: Custom Formatting Function with Regular Expression
Regular expressions, or regex, provide a powerful pattern for identifying and manipulating strings.
By using regex, we can find a specific substring from a given string and replace or convert it into our desired pattern. In this discussion, we are using regex to add commas to a number solely for formatting purposes.
We will use the string replace() method and provide a regular expression to apply our number formatting.
Look at the following code: We first convert a number into a string using the JS inbuilt tostring() method. Then we will use the expression “/\B(?=(\d{3})+(?!\d))/g” within the replace() method. This regular expression will find and apply a comma separator where applicable.
<script>
var num = 1000000;
// Apply a regular expression within replace method
// To achieve our desired number formatting
var commaSeperatedNumber = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
console.log(commaSeperatedNumber); // Output: 1,000,000
</script>
No. 5: JavaScript format number with Commas and 2 Decimal Places
Using toLocaleString Method
When you need to format numbers with commas and 2 decimal places or 3 decimal places, you can easily modify the toLocaleString method for rounding numbers as well. Just apply the minimumFractionDigits and maximumFractionDigits options to the second parameter of the localeString method.
Make sure that the values of the minimumFractionDigits and maximumFractionDigits options are equal. Otherwise, you will end up with unexpected formats.
<script>
var num1 = 1234567;
var num2 = 1234567.789;
var num3 = 1234567.234;
const options = {
minimumFractionDigits: 2,
maximumFractionDigits: 2
};
var commaSeperatedNumber1 = num1.toLocaleString('en-US',options);
// Check rounding number issue upto 2 decimal points
var commaSeperatedNumber2 = num2.toLocaleString('en-US',options);
// Check rounding number issue upto 2 decimal points
var commaSeperatedNumber3 = num3.toLocaleString('en-US',options);
console.log(commaSeperatedNumber1); // Output: 1,234,567.00
console.log(commaSeperatedNumber2); // Output: 1,234,567.79
console.log(commaSeperatedNumber3); // Output: 1,234,567.23
</script>
Using Intl.NumberFormat
We can apply the same style parameters as the toLocaleString() method. We used the same numbers and the same formatter. And received the same output as well. Look at the code below:
<script>
var num1 = 1234567;
var num2 = 1234567.789;
var num3 = 1234567.234;
var options = {
minimumFractionDigits: 2,
maximumFractionDigits: 2
};
const formatter = new Intl.NumberFormat('en-US',options);
var commaSeperatedNumber1 = formatter.format(num1);
var commaSeperatedNumber2 = formatter.format(num2);
var commaSeperatedNumber3 = formatter.format(num3);
console.log(commaSeperatedNumber1); // Output: 1,234,567.00
console.log(commaSeperatedNumber2); // Output: 1,234,567.79
console.log(commaSeperatedNumber3); // Output: 1,234,567.23
</script>
Difference Between toLocaleString() and Intl.NumberFormat
Now a question may arises what is the difference between toLocaleString() and Intl.NumberFormat. Basically there are 5 main differences between them. These are:
- Intl.NumberFormat is more flexible and option reach than toLocaleString().
- toLocaleString() is very easy to use.
- toLocaleString() is used for simple number formatting whereas Intl.NumberFormat is used for long numbers.
- Due to simplicity toLocaleString() is faster than Intl.NumberFormat.
- Intl.NumberFormat follows the newest rules for how to format numbers. But toLocaleString() may not work in every devices.
Our Recommendation Considering JavaScript Format Number with Commas
Our recommendation is to use Intl.NumberFormat for enterprise level applications. Otherwise use toLocaleString().
JavaScript Format Number with Commas Using the toFixed() Method
Sometimes you may require only “javascript format number with commas” and sometimes you may require “javascript round to 2 decimal” or even both. So here we are going to build an example of how JS formats numbers with commas, along with rounding the number up to a specific decimal, such as two or three.
<script>
var numDecimals = 1234567.789;
var num = numDecimals.toFixed(2);
const formatter = new Intl.NumberFormat('en-US');
var commaSeperatedNumber = formatter.format(num);
console.log(commaSeperatedNumber); // Output: 1,234,567.79
</script>
Here is the is the first round, and convert the number to a string to make sure that two decimal points are available. Later on, apply the integer format in general. So the combined output will produce a comma-separated number with two decimal points.
Conclusion
We hope that, from our detailed discussion, you have learned a lot about how “javascript format number with commas” works. We have also provided all possible examples of code along with their corresponding outputs so that you can grasp the concept easily without running a single line of code.
We also elaborated on why and when to use which method to avoid confusion in your mind.
We also discussed how to use different types of available styles for different units, such as currencies.
So use the appropriate method based on your needs. Apply appropriate number formats to display numbers that meet your design goals.
If you have any concerns, comments, or feedback, please feel free to leave them below.
FAQs on “JavaScript Format Number with Commas”
How to add a comma after 3 digits in JavaScript?
If you are not clear about the user locale or want to fix the format for thousand separator then use the regular expression ‘/\B(?=(\d{3})+(?!\d))/g’ to add a comma separation after 3 fixed digits.
How to print a number with commas as thousands separators in JavaScript?
There are 5 ways you can print a number with commas as thousands separator. These are:
1. toLocaleString Method
2. Intl.NumberFormat
3. Numeral.js Library
4. Regular Expression
5. Combined toFixed() Method
To get detail with example code please read this article from first to last.
How to Format a Number as Currency in JavaScript?
You can use different options for different locale like below:
var options = {
style: ‘currency’,
currency: “USD”,
currencyDisplay: ‘symbol’,
notation: ‘compact’
};
Pass the options as second parameter of toLocaleString method or Intl.NumberFormat. Read the whole article to understand more.
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply