[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:
10
1.7777777
9.1
Output:
10
1.78
9.1
How can we do this in JavaScript ?
Solution 1:
The rounding problem can be avoided by using numbers represented in exponential notation:
Number(Math.round(1.005+'e2')+'e-2'); // 1.01
To abstract that into something more usable
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // 1.01
Solution 2:
Try this:
Math.round(num * 100) / 100.
Read Also
Php Show number 2 decimal placesSolution 3:
You can use this:
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
This code helps to round up 2 digits after the decimal.
roundToTwo(1.005)
1.01
roundToTwo(10)
10
roundToTwo(1.7777777)
1.78
roundToTwo(9.1)
9.1
Solution 4:
This solution have generic extension for any number of decimal places.
Number.prototype.round = function(places) {
return +(Math.round(this + "e+" + places) + "e-" + places);
}
Usage:
var n = 1.7777;
n.round(2); // 1.78
Unit test:
it.only('should round floats to 2 places', function() {
var cases = [
{ n: 10, e: 10, p:2 },
{ n: 1.7777, e: 1.78, p:2 },
{ n: 1.005, e: 1.01, p:2 },
{ n: 1.005, e: 1, p:0 },
{ n: 1.77777, e: 1.8, p:1 }
]
cases.forEach(function(testCase) {
var r = testCase.n.round(testCase.p);
assert.equal(r, testCase.e, 'didn\'t get right number');
});
})
Read Also
Validate Decimal Numbers.Solution 5:
Using this code .toFixed(NumberOfDecimalPlaces).
var str = 10.234.toFixed(2); // => '10.23'
var number = Number(str); // => 10.23
Solution 6:
This code have .toFixed(2))
for fixed values.
Number((1.005).toFixed(2)); // 1 instead of 1.01