Rounding to Two Decimal Places, if Necessary in JavaScript
You want to round a number up to two decimal places, but only if it has more than two decimal places. For instance, 10 should remain unchanged, 1.7777777 should become 1.78, and 9.1 should stay as is.
Solutions:
There are two approaches you can take in JavaScript:
1. Using Math.round()
Math.round(num * 100) / 100
2. Using Number.EPSILON
Math.round((num + Number.EPSILON) * 100) / 100
Sample Input and Output:
Input | Using Math.round() | Using Number.EPSILON |
---|---|---|
10 | 10 | 10 |
1.7777777 | 1.78 | 1.78 |
9.1 | 9.1 | 9.1 |
1.005 | 1 | 1.01 |
The above is the detailed content of How to Round Numbers to Two Decimal Places in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!