How to Format a Number with Two Decimals in JavaScript
There are several methods used to format a number with two decimals in JavaScript. Let’s see the difference between the methods.
Intl.NumberFormat
You can use the Intl.NumberFormat constructor. It is supported in major browsers and in Node.js:
toLocaleString
The alternative of the above method is the toLocaleString method which internally uses the Intl API:
toFixed
One of the methods used is the toFixed method which returns a string:
For example:
To round the number, you should use the math.round() function which returns the value of a number rounded to the nearest integer:
Numbers
The Number object is a wrapper object that allows working with numerical values. There are two types of numbers in modern JavaScript: Regular and BigInt. The math is a built-in object that has properties and methods for mathematical constants and functions. The math object works with the Number type not with BigInt.