[Solved-6 Solutions] Round to at most 2 decimal places - javascript tutorial
Problem:
To round at most 2 decimal places, but only if necessary.
Input:
Output:
How can we do this in JavaScript ?
Solution 1:
The rounding problem can be avoided by using numbers represented in exponential notation:
To abstract that into something more usable
Solution 2:
Try this:
Math.round(num * 100) / 100.
Read Also
Php Show number 2 decimal placesSolution 3:
You can use this:
This code helps to round up 2 digits after the decimal.
Solution 4:
This solution have generic extension for any number of decimal places.
Usage:
Unit test:
Read Also
Validate Decimal Numbers.Solution 5:
Using this code .toFixed(NumberOfDecimalPlaces).
Solution 6:
This code have .toFixed(2))
for fixed values.