Formatting Numbers with Precision in JavaScript
To display numbers with exactly two decimal places in JavaScript, one can leverage the toFixed() method. Here's how:
var price = 10.8; var formattedPrice = price.toFixed(2); // "10.80"
Note that toFixed() returns a string, not a number.
Limitations of toFixed()
While toFixed() can round most numbers correctly, it doesn't round consistently in all cases. For example:
2.005.toFixed(2) === "2.00"
Intl.NumberFormat for Precision Formatting
For precise number formatting, the Intl.NumberFormat constructor is recommended. It's fully supported in modern browsers, including IE11, and in Node.js:
const formatter = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(formatter.format(2.005)); // "2.01" console.log(formatter.format(1.345)); // "1.35"
Intl.NumberFormat provides more control and consistency in number formatting compared to toFixed().
The above is the detailed content of How Can I Precisely Format Numbers to Two Decimal Places in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!