Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to print a number with commas as thousands of 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
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>
Input : 1234567890 Output: 1,234,567,890
Using Intl.NumberFormat() Object
Intl is the internationalization namespace in JavaScript. Language-sensitive number formatting is one of the uses of this method.
Syntax
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>
Input : 1234567890 Output: 1,234,567,890
Using Regular Expression
We can write our code using regex to format numbers.
Syntax
number.toString().split(".");
number.replace(regex, ",");
Algorithm
STEP 1 ? Convert 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>
<p id="regxOut"></p>
<script>
const regxNum = 192837.4650;
document.getElementById("regxInp").innerHTML = "Input = " + regxNum;
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);
document.getElementById("regxOut").innerHTML = "Output = " + regxFormt;
</script>
</body>
</html>
Input = 192837.465 Output = 192,837.465
Using Custom Function
Here we have written custom code to comma separate the number by checking decimal places and signs.
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>
<p id="custOut"></p>
<script>
let custNum = -987654.4650;
document.getElementById("custInp").innerHTML = "Input = " + custNum;
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);
document.getElementById("custOut").innerHTML = "Output = " + custFormt;
</script>
</body>
</html>
Input = -987654.465 Output = -987,654.465
Comparison
| Method | Performance | Locale Support | Complexity |
|---|---|---|---|
toLocaleString() |
Moderate | Yes | Simple |
Intl.NumberFormat() |
Moderate | Yes | Simple |
| Regular Expression | Fast | No | Moderate |
| Custom Function | Fast | No | Complex |
Conclusion
For internationalization needs, use toLocaleString() or Intl.NumberFormat(). For high-performance formatting without locale support, regular expressions or custom functions are faster alternatives.
