JavaScript Add Commas to Number


In this tutorial, we will explore how to add commas to numbers in JavaScript. Adding commas to numeric values is a common requirement when displaying large numbers in a more readable format.

We will discuss different methods to achieve this formatting, allowing you to enhance the presentation of numerical data in your web applications. So, let's get started and learn how to add commas to numbers in JavaScript!

    Table of Contents

  1. Using the toLocaleString() method
  2. Utilizing Regular Expressions
  3. Using a third-party library
  4. Conclusion

1. Using toLocaleString() method

The toLocaleString() method is a built-in function that can be used to format a number with commas.

It is supported by all modern browsers and is the simplest way to add commas to numbers in JavaScript.

Example

const number = 1000000;
const formattedNumber = number.toLocaleString();

console.log(formattedNumber); // Output: 1,000,000

By using toLocaleString(), the number is converted into a string representation with comma-separated thousands, based on the user's locale settings.


2. Utilizing Regular Expressions

Regular expressions are powerful tools for pattern matching and string manipulation. They can also be used to add commas to numbers in JavaScript.

The following code snippet shows how to use regular expressions to add commas to numbers in JavaScript.

Example

const number = 1000000;
const formattedNumber = number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

console.log(formattedNumber); // Output: 1,000,000

The regular expression used in the above code is \B(?=(\d{3})+(?!\d)). Let's break it down to understand how it works.


3. Using a third-party library

If you prefer a more comprehensive solution, you can utilize a third-party library like Numeral.js or accounting.js. These libraries provide advanced number formatting options, including adding commas to numbers.

Let's see how to use Numeral.js to add commas to numbers in JavaScript.

const numeral = require('numeral');

const number = 1000000;
const formattedNumber = numeral(number).format('0,0');

console.log(formattedNumber); // Output: 1,000,000

Using such libraries gives you additional flexibility and control over number formatting, allowing for more complex formatting requirements.


Conclusion

Adding commas to numbers improves readability and enhances the presentation of numeric data in your web applications. Now that you know how to add commas to numbers in JavaScript, you can use this knowledge to format numbers in your web applications.

Check out number formatting in JavaScript in detail.

That's all for this tutorial. Happy Coding!