according to mathematics i thought that :
// Round change to the nearest hundreth deals with precision errors
change = Math.round(change * 100) / 100;
}
**should be same as **
// Round change to the nearest hundreth deals with precision errors
change = Math.round(change);
}
**since that **
(2.05 * 100) / 100 = 2.05
According to MDN
The Math.round()
function returns the value of a number rounded to the nearest integer.
So if change
is a decimal number, you will not get the same result.
1 Like
snigo
August 7, 2020, 7:59pm
3
You can always write your own round that will round numbers according to given precision, or take one of million already written rounding functions (as they are in a good demand) and open sourced for everyone to use, like this one I’ve made for example:
function round(num, precision = 12) {
return +(+(num * 10 ** precision).toFixed(0) * 10 ** -precision)
.toFixed(precision < 0 ? 0 : precision);
}
round(0.1 + 2.2, 2); // 2.3
round(2020, -2); // 2000
1 Like
const change1 = 2.05;
console.log(Math.round(change1 * 100) / 100);
// 2.05
console.log(Math.round(change1));
// 2
const change2 = 2.049;
console.log(Math.round(change2 * 100) / 100);
// 2.05
console.log(Math.round(change2));
// 2
And don’t confuse Math.round(change * 100) / 100
with Math.round(change * 100 / 100)
- they are not the same thing.
1 Like