2

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));
Svenmarim
  • 3,633
  • 5
  • 24
  • 56

2 Answers2

2

Floating points in JavaScript is broken as @Jaromanda and @dan_pran mentioned.

But the Math.round() solution still works for your use case - it's just a bit more code:

Number.prototype.round = function (precision = 2) {
  return Math.round(this * 10 ** precision) / 10 ** precision;
}

const value = 51.425;
console.log('Rounded with 3 decimals: ', value.round(2));

const value2 = 51.4251;
console.log('Rounded with 4 decimals: ', value2.round(2));

const value3 = 51.4215;
console.log('Rounded with 4 decimals: ', value3.round(3));
technophyle
  • 7,972
  • 6
  • 29
  • 50
1

You can set the number of digits after the decimal with a multiplier equal to 10**number

Number.prototype.round = function(number = 2) {
  let m = 10 ** number
  return Math.round(this.valueOf() * m) / m;
}

for (let i = 0; i <= 10; i++) {

  console.log(Math.PI.round(i))

}
Arleigh Hix
  • 9,990
  • 1
  • 14
  • 31