Home >Web Front-end >JS Tutorial >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!