Home > Web Front-end > JS Tutorial > How Can I Precisely Format Numbers to Two Decimal Places in JavaScript?

How Can I Precisely Format Numbers to Two Decimal Places in JavaScript?

Barbara Streisand
Release: 2024-12-31 06:24:14
Original
766 people have browsed it

How Can I Precisely Format Numbers to Two Decimal Places in JavaScript?

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"
Copy after login

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"
Copy after login

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"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template