Format a Number with Commas in React

When we are working with a large number, especially in Front End we need to format the number with commas to make it more readable.

In this article, we will discuss built-in JavaScript methods Intl.NumberFormat and toLocaleString() to format numbers with commas in React.

1. Using the Intl.NumberFormat method

To format a number with commas in React, we can use the Intl.NumberFormat method.

This method takes two arguments: a locale and an options object.

The locale argument specifies the locale to use for formatting, and the options object specifies the formatting options.

For example, to format a number with two decimal places for a US (thousand, million, and billion separators) audience, we would use the following:

React
import React from "react";

export default function App() {
  const num = 123456.789;
  const options = {
    maximumFractionDigits: 2
  }

  const formattedNumber = Intl.NumberFormat("en-US",options).format(num);

  return <h2>{formattedNumber}</h2>;
}

//👉 123,456.78

We passed en-US as the locale to the Intl.NumberFormat, and to round the number to two decimal places, we used the maximumFractionDigits option.

There are many other options for formatting a number, such as units, scientific numbers, etc.

If no option is passed to the Intl.NumberFormat object, it will use the locale as per the browser’s preference.

JavaScript
const num = 123456.789;

console.log(new Intl.NumberFormat().format(num));
//👉 123,456.789   USA

2. Using the toLocaleString() method

Another method you can use is to use the toLocaleString() method. This method is available on all numbers and accepts the same arguments as the Intl.NumberFormat() method.

JavaScript
const num = 123456.789;

const options = {
    maximumFractionDigits: 2
}

const formattedNumber = num.toLocaleString('en-US', options);

// 👉 123,456.79

We used toLocaleString(), which works the same way as Intl.NumberFormat().


Conclusion

We learned how to format numbers with commas in React using the Intl.NumberFormat() and toLocaleString() methods. We also looked at some of the benefits of using these methods, such as the ability to localize number formatting for different regions.

Learn More:

Can we Format a Number with Commas in React?

Format a Number with Commas

Yes, using the Intl.NumberFormat and toLocaleString() method, we can format numbers with commas in React.

Does React Have any built in method to format a number with commas?

Format a Number with Commas

Yes, React has the Intl.NumberFormat and toLocaleString() built-in method to format numbers with commas in React.

Unlock your programming potential with Stack Thrive! Discover step-by-step tutorials, insightful tips, and expert advice that will sharpen your coding skills and broaden your knowledge.

Leave a Comment

Facebook Twitter WhatsApp