Sometimes, we want to format a number with commas in React.
In this article, we’ll look at how to format a number with commas in React.
How to format a number with commas in React?
To format a number with commas in React, we can use the number’s toLocaleString
method.
For instance, we write:
import React from "react";
export default function App() {
return (
<div>
{(1234.56789).toLocaleString(undefined, { maximumFractionDigits: 2 })}
</div>
);
}
We call toLocaleString
on 1234.56789
with { maximumFractionDigits: 2 }
to return a number string that has the comma digit separators and the rounded to 2 decimal places.
Therefore, we see 1,234.57 displayed.
Conclusion
To format a number with commas in React, we can use the number’s toLocaleString
method.