When trying to round a number with 3 decimals to a number with 2 decimals, toFixed()
doesn't round the latest number correctly. But when I do the same thing with a number with 4 decimals, it does work... I can't wrap my mind about it how that can be.
I have seen some solutions like Math.round(value * 100) / 100
, but then it always rounds down to 2 decimals, while I want a generic function to round, where you can enter the number of decimals to round to.
Currently the function is like this:
Number.prototype.round = function (precision: number = 2) {
return Number(this.toFixed(precision));
}
Any ideas on how to solve this issue?
const value = 51.425;
console.log('To fixed with 3 decimals: ', value.toFixed(2));
const value2 = 51.4251;
console.log('To fixed with 4 decimals: ', value2.toFixed(2));