
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print Number with Commas as Thousands Separators in JavaScript
In this tutorial, we will look at a few ways to print a number with commas as thousands of separators in JavaScript and compare them to understand which one is suitable in a given context.
Why do we do number formatting? In English, commas are used to separate numbers bigger than 999. Dot is the thousands separator in Germany. Sweden uses space. The separator is added after every three digits from the right.
Let's briefly introduce the methods.
Using the toLocaleString() Method
Here, the built-in locale string method localizes the number format based on the country.
Syntax
Users can follow the syntax below.
number.toLocaleString(locale)
Here, the number is the number that we are going to separate with commas.
Parameters
locale ? The locale code of the country. For the USA, it is ?en-US'. ?en' is the English language, and ?US' is the USA. Other examples are en-GB, hi-EN, and ar-EG. hi-EN uses a comma after every two digits.
Example
In this program, the toLocaleString() returns the comma-separated number of the input.
<html> <body> <p id="inp"></p> <p id="out"></p> <script> const num = 1234567890; document.getElementById("inp").innerHTML = "Input : " + num; const result = num.toLocaleString('en-US'); document.getElementById("out").innerHTML = "Output: " + result; </script> </body> </html>
Using Intl.NumberFormatter() Object
Intl is the internationalization namespace in JavaScript. Language-sensitive number formatting is one of the uses of this method.
Syntax
Users can follow the syntax below.
new Intl.NumberFormat() new Intl.NumberFormat(locale) new Intl.NumberFormat(locale, options)
Here, Intl refers to internationalization.
Parameters
locale ? The locale code. For example, ?en-IN', ?de-DE', 'ja-JP.'
options ? There are many options available, like style, currency, etc.
Example
When the user clicks the button, the Intl object formats the number and displays the output.
<html> <body> <p>Print a number with a commas separator using Intl.NumberFormat</p> <p id="inp"></p> <p id="out"></p> <script> const num = 1234567890; document.getElementById("inp").innerHTML = "Input : " + num; const result = Intl.NumberFormat('en-US').format(num); document.getElementById("out").innerHTML = "Output: " + result; </script> </body> </html>
Using Regular Expression
We can write our code using regex to format numbers.
Syntax
Users can follow the syntax below.
number.toString().split("."); number.replace(replace, ",");
Here, the string split and replace syntax used in the example is given.
Algorithm
STEP 1 ? Covert the number to a string.
STEP 2 ? Split into a number and a possible decimal.
STEP 3 ? Use regex to find and add commas to thousands (3-digit group) in the number.
STEP 4 ? Separate the number and decimal with a dot.
Example
In this example, the input is grouped into three digits using the custom regex.
<html> <body> <h3>Print a number with a commas separator using regex</h3> <p id="regxInp"></p> <div id="regxWrap"> <p>Click the below button</p> <button onclick="regxDoFormat()">Click Me</button> </div> <p id="regxOut"></p> <script> const regxNum = 192837.4650; var regxInpEl = document.getElementById("regxInp"); var regxOutEl = document.getElementById("regxOut"); var regxBtnWrapEl = document.getElementById("regxWrap"); regxInpEl.innerHTML = "Input = " + regxNum; function regxDoFormat() { function formatNum(n) { var splits = n.toString().split("."); const numSplit = splits[0]; const decimalSplit = splits[1]; const thousands = /\B(?=(\d{3})+(?!\d))/g; return numSplit.replace(thousands, ",") + (decimalSplit ?"." + decimalSplit : ""); } const regxFormt = formatNum(regxNum); regxOutEl.innerHTML = "Output = " + regxFormt; regxBtnWrapEl.style.display = "none"; } </script> </body> </html>
By Creating Custom Function
Here we have written custom code to comma separate the number by checking decimal places and signs.
Syntax
number.toString().includes('.); number.toString().split('.')[0]; for (initialize; condition; loop control) {}
Here the syntax of string operations and loop used in the example is given.
Algorithm
Check for the decimal point and number sign.
Remove the sign, loop through, and add commas to 3 digits group accordingly.
Add the sign back and display the output.
Example
Here, the negative floating point input is processed by the custom code based on the algorithm above, and the desired output is obtained.
<html> <body> <h3>Print a number with a commas separator using custom code</h3> <p id="custInp"></p> <div id="custWrap"> <p>Click this button</p> <button onclick="custDoFormat()">Click Me</button> </div> <p id="custOut"></p> <script> let custNum = -987654.4650; var custInpEl = document.getElementById("custInp"); var custOutEl = document.getElementById("custOut"); var custBtnWrapEl = document.getElementById("custWrap"); custInpEl.innerHTML = "Input = " + custNum; function custDoFormat() { function addComma(numVal) { // remove numSign var numSign = 1; if (numVal < 0) { numSign = -1; numVal = -numVal; } // trim the decimal point let num = numVal.toString().includes('.') ? numVal.toString().split('.')[0] : numVal.toString(); let len = num.toString().length; let numResult = ''; let numCount = 1; for (let i = len - 1; i >= 0; i--) { numResult = num.toString()[i] + numResult; if (numCount % 3 === 0 && numCount !== 0 && i !== 0) { numResult = ',' + numResult; } numCount++; } // include number after decimal point if (numVal.toString().includes('.')) { numResult = numResult + '.' + numVal.toString().split('.')[1]; } // return numResult with numSign return numSign < 0 ? '-' + numResult : numResult; } let custFormt = addComma(custNum); custOutEl.innerHTML = "Output = " + custFormt; custBtnWrapEl.style.display = "none"; } </script> </body> </html>
This article discusses three ways to print a number with commas as thousands of separators in JavaScript.
The locale string and Intl number format method must first look for the localization chosen by the JavaScript engine. Then only formatting is done.
The regex and string replace method is faster than the toLocaleString() method. You can go for this method when there are a huge number of formatting requests.