Home >Web Front-end >JS Tutorial >How to Round Numbers to Two Decimal Places in JavaScript Only When Necessary?

How to Round Numbers to Two Decimal Places in JavaScript Only When Necessary?

DDD
DDDOriginal
2024-12-28 00:21:09617browse

How to Round Numbers to Two Decimal Places in JavaScript Only When Necessary?

Rounding Numbers to Two Decimal Places: When Necessary

If you want to round numbers to at most two decimal places, but only when necessary, here are two effective methods in JavaScript:

1. Using Math.round():

Math.round(num * 100) / 100

This method multiplies the number by 100 to move the decimal point two places to the right, rounds the result using Math.round(), and then divides by 100 to move the decimal point back to its original position.

2. Using Number.EPSILON for Precision:

Math.round((num + Number.EPSILON) * 100) / 100

This method is more precise, especially for numbers like 1.005 that may be incorrectly rounded by the previous method due to floating-point precision issues. It adds a small number (Number.EPSILON) before multiplying and rounding, ensuring that no rounding errors occur.

Example Usage:

const numbers = [10, 1.7777777, 9.1];
const roundedNumbers = numbers.map(num => {
  return num === Math.floor(num)
    ? num
    : Math.round(num * 100) / 100;
});

console.log(roundedNumbers); // Output: [10, 1.78, 9.1]

In this example, numbers are rounded to two decimal places only if they have a fractional part. 10 remains unchanged as it's already an integer.

The above is the detailed content of How to Round Numbers to Two Decimal Places in JavaScript Only When Necessary?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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