Big Numbers, No Worries: JavaScript Format Number With Commas
Tags: webdev, javascript, programming, tutorial
Published: 2024-03-23 12:02:40

If you are a web developer, you may have encountered the challenge of formatting numbers with commas in JavaScript. For example, you can display a large number, like 1000000 or 1,000,000, for better readability. Using the `toLocaleString()` method you can format numbers with commas. This is a handy skill to master, and there are different methods to do it in JavaScript.

In this blog post, I will show you:

*   Five different ways to format numbers with commas
*   Adding decimals to formatted numbers
*   Formatting numbers as currency
*   Updating formatted numbers in real-time
*   Adapting to different locales and formats
*   Exploring advanced number formatting techniques

By the end of this post, you will be able to format any number with commas in JavaScript easily and efficiently.

## Understanding number formatting in JavaScript

Sometimes, numbers can be hard to read or understand without comma separators. That’s why you need to format them in a way that makes sense to humans. For example, adding commas to separate the digits of large numbers, or showing the percentage sign or the currency symbol.

In JavaScript, you have many options to format numbers with commas. In this article, I will show you five different methods.

If you don't have time to read the whole article, here is the summary:

![5 Different Ways: JavaScript Format Number With Commas](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oc9qr6suqk97rwj05amy.png)

## Method 1: JavaScript format number with commas using toLocaleString()

Do you want to make your numbers look more readable and friendly? You can do that with the `toLocaleString()` method in JavaScript! This method lets you format numbers based on the user’s location and preferences. It adds commas where they are needed, so you can easily see the thousands, millions, or billions.

Here is how you can use the `toLocaleString()` method to format numbers with commas in JavaScript:

```
const number = 1234567.89;
const formattedNumber = number.toLocaleString(); 
console.log(formattedNumber)
// Output: "1,234,567.89"
```


Isn’t it awesome how the `toLocaleString()` method can make numbers look nicer? It adds commas automatically, so you don’t have to worry about counting digits. But that’s not all!

You can also customize how the number is formatted with the options parameter. This is an object that lets you choose things like how many decimal places you want, what currency symbol to use, and what style of number you need.

Here’s an example of how to use the options parameter:

```
// Declare a number variable
var number = 1234567.89;
// Define the formatting options
var options = {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
  style: "currency",
  currency: "INR"
};
// Format the number using the toLocaleString() and the options
var formattedNum = number.toLocaleString("en-IN", options);
// Display the formatted number
console.log(formattedNum);
// Output: ₹ 12,34,567.89
```


![JavaScript Format Number With Commas using toLocaleString()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06ubpq0h8wovniywfkiy.png)

Did you know that the `toLocaleString()` method can make your web pages more awesome? It can automatically adjust to the local ways of writing numbers, JavaScript dates, and times in different languages and regions. This means your web pages can be more friendly and easy to understand for people from all over the world.

But there is a catch. Some older browsers may not know how to use this method, and it may not work the same way on different platforms and devices. So you may need to check the compatibility and consistency of your code before using it.

## Method 2: Format number with commas using Intl.NumberFormat() object

The second method to format numbers with commas in JavaScript is to use the `Intl.NumberFormat()` object. This object is similar to the toLocaleString() method, but it provides more control and flexibility over the formatting options. The `Intl.NumberFormat()` object is part of the `ECMAScript` Internationalization API, which is a standard for internationalizing and localizing JavaScript.

To use the `Intl.NumberFormat()` object, you need to create an instance of it using the `new` keyword, and pass the desired locale and options as arguments. Then, you can use the `format()` method of the instance to format a number.

For example, if you want to format a number with commas using the English (United States) locale, you can use the following code:

```
// Declare a number variable
var number = 1234567.89;
// Create an instance of the Intl.NumberFormat object
var formatter = new Intl.NumberFormat("en-US");
// Format the number using the format() method
var formattedNumber = formatter.format(number);
console.log(formattedNumber); 
// Output: 1,234,567.89
```


You can make numbers look nicer with `Intl.NumberFormat()`. It has an options object that lets you change how the number looks. You can use the same options as `toLocaleString()`.

Here’s how to use the options:

```
// Declare a number variable
var number = 1234567.89;
// Define the formatting options
var options = {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
  style: "currency",
  currency: "INR"
};
// Create an instance of the Intl.NumberFormat object
var formatter = new Intl.NumberFormat("en-IN", options);
// Format the number using the format() method
var formattedNum = formatter.format(number);
console.log(formattedNum); 
// Output: ₹ 12,34,567.89
```


![JavaScript Intl.NumberFormat() method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/79g1t5ahrv3uxqfe3pr1.png)

`Intl.NumberFormat()` makes sure your numbers look the same everywhere, no matter what browser, platform, or device you use. It follows the newest rules for how to format numbers.

But it’s not perfect. Some old browsers don’t know how to use it and it might slow down your code a bit compared to `toLocaleString()`.

## Method 3: Using a regular expression with the replace() method

Here’s a simple way to format numbers with commas: use regular expressions and the `replace()` method! Regular expressions are like magic spells that help you find and change parts of a string. The `replace()` method is a handy method that lets you swap one string for another. Together, they can make any number look nice and neat with commas.

Here’s how you do it:

```
// Declare a number variable
var number = 1234567.89;
// Define a regular expression that matches groups of three digits
var regex = /(\d)(?=(\d{3})+(?!\d))/g;
// Define the replacement string that adds a comma
// after each group of three digits
var replacement = "$1,";
// Format the number using the replace() method
var formattedNum = number.toString().replace(regex, replacement);
// Display the formatted number
console.log(formattedNum); 
// Output: 1,234,567.89
```


You can turn a number into a string with [JavaScript toString()](https://www.rajamsr.com/javascript-tostring/). Then you can use `replace()` with a special pattern. This pattern lets us format the number however you want. You don’t need any extra tools or codes for this. But this way can be tricky and risky. Sometimes it might not work well for some numbers or situations.

## Method 4: Format the number with a comma using the toFixed() method

Here’s a cool trick to make numbers look nice in JavaScript. It’s called the [JavaScript toFixed()](https://www.rajamsr.com/javascript-math-tofixed/) method. It lets you turn a number into a [JavaScript string](https://www.rajamsr.com/javascript-string/) and pick how many decimals you want. For example, `toFixed(2)` will round the number to two decimals and add a dot.

Look at this example of using `toFixed()` in JavaScript:

```
// Format number with comma using toFixed()
var number = 123456789.123;
// Convert the numberber into a string, with two decimal places
var fixednumber = number.toFixed(2);
// Split the string into two parts: the integer part and the decimal part
var parts = fixednumber.split(".");
// Add commas to the integer part, using a regular expression
var integerPart = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
// Join the two parts with a dot
var formattednumber = integerPart + "." + parts[1];
// Display the formatted numberber
console.log(formattednumber); 
// Output: 123,456,789.12
```


![Format Numbers using JavaScript toFixed() Method
](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wx6uvdb845kj1afjtojb.png)

The `toFixed()` method is awesome because it works on all browsers.

But it also has a drawback. It is not very simple and easy. You have to do a lot of stuff and use many operations, like splitting, replacing, and [JavaScript string join](https://www.rajamsr.com/javascript-string-join/). You also have to use a regular expression, which is a powerful but tricky method that can find and change patterns in strings.

## Method 5: Format number with commas using a Third-Party library Numeral.js

You can use a third-party library, which is a bunch of code that someone else wrote for you. Many awesome third-party libraries can format numbers with commas in JavaScript. For example, you can try [Numeral.js](https://www.npmjs.com/package/numeral), [Accounting.js](https://openexchangerates.github.io/accounting.js/), or [Format.js](https://formatjs.io/).

Let me show you how to use `Numeral.js`, one of the most popular and easy-to-use libraries. It’s super simple to format numbers with commas in JavaScript using `Numeral.js`:

```
// Load the Numeral.js library from a CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js">
</script>
// Declare a number variable
var num = 123456789.123;
// Format the number using the Numeral.js library
var formattedNum = numeral(num).format("0,0.00");
// Display the formatted number
console.log(formattedNum); 
// Output: 123,456,789.12
```


Third-party libraries are awesome! They can help you format numbers with commas in JavaScript in a snap. You just need to get the library from somewhere, like a CDN or your file. Then you use its methods and functions and voila!

However third-party libraries also have a downside. They can make your web page bigger and slower. Some libraries have a lot of code that you might not use or need. This can affect the speed and experience of your web page. So you should always be careful before using a third-party library.

## Formatting numbers with commas and decimal places

Let’s check out some real-time use cases of formatting numbers with commas.

When you need to format numbers with both commas and round to two decimal places, you can extend the `toLocaleString()` method to include options for decimal formatting.

```
const number = 1234567.89123;
const options = { 
  style: 'decimal', 
  maximumFractionDigits: 2 
};
const formattedNumber = number.toLocaleString(undefined, options);
console.log(formattedNumber)
// Output: "1,234,567.89"
```


By specifying the `maximumFractionDigits` option, you can control the number of decimal places displayed.

## JavaScript format number as currency with commas

Formatting numbers as currency is common in e-commerce and financial applications. You can use JavaScript’s `toLocaleString()` method to format currency.

Here is an example of formatting numbers as currency with commas:

```
const amount = 1234567.89;
const currencyOptions = { 
  style: 'currency', 
  currency: 'USD' 
};
const formattedAmount = amount.toLocaleString('en-US', currencyOptions);
console.log(formattedAmount)
// Output: "$1,234,567.89"
```


You can customize the `currency symbol` and `locale` to match your application’s requirements.

## Handling locale-specific number format in JavaScript with comma

Different locales have different conventions for number formatting. JavaScript’s `Intl.NumberFormat()` method provides a way to format numbers based on the user’s locale.

```
const number = 1234567.89;
const formattedNumber = new Intl.NumberFormat('de-DE').format(number); 
console.log(formattedNumber)
// "1.234.567,89"
```


You can format numbers correctly for different regions by passing the appropriate locale to the constructor. This example passes the `German` locale `de-DE` as a parameter.

## Conclusion
In this blog post, you have learned how to format numbers with commas in JavaScript using five different methods: the `toLocaleString()` method, and the `Intl.NumberFormat()` object, and a regular expression with the `replace()`, using `toFixed()` and using a third-party library.

You have also seen some real-time code examples of basic number formatting, formatting numbers with decimals and commas, formatting currency with commas, and handling locale-specific formatting.

Whether you’re formatting large quantities, currencies, or percentages, JavaScript provides a range of options to meet your formatting needs. By using the appropriate method for your needs, you can display numbers in a way that suits your target audience and your design goals.

I hope you have found this blog post helpful and informative. If you have any questions, comments, or feedback, please feel free to leave them below. 😊

---
If you want to stay connected with me and get more updates on my work, you can follow me on different platforms.

[Website](https://www.rajamsr.com) | [X/Twitter](https://twitter.com/rajamsrtweets) | [LinkedIn](https://www.linkedin.com/in/rajamsr/)