Home > Web Front-end > JS Tutorial > How to Always Display Two Decimal Places in a Number?

How to Always Display Two Decimal Places in a Number?

Susan Sarandon
Release: 2024-12-22 22:36:16
Original
559 people have browsed it

How to Always Display Two Decimal Places in a Number?

How to Format Numbers to Always Display 2 Decimal Places

To format numbers to always display two decimal places, rounding where applicable, we can use the following formula:

(Math.round(num * 100) / 100).toFixed(2);
Copy after login

This formula first multiplies the number by 100, rounding the result to the nearest integer. It then divides the rounded result by 100, effectively reverting the multiplication. Finally, it uses the toFixed(2) method to format the number to two decimal places.

Example:

let num = 1.345;
let formattedNum = (Math.round(num * 100) / 100).toFixed(2);
console.log(formattedNum); // Output: 1.35
Copy after login

This formula ensures that numbers are always displayed with two decimal places, regardless of the original number. It rounds the number to the nearest hundredth, so that even numbers like 1 will be formatted as "1.00."

The above is the detailed content of How to Always Display Two Decimal Places in a Number?. 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