-1

Different types of rounding and different result

Why is it, I was checking the mathematics rules, where was saying that after 0.5 we are rounding to 1 but in the second operation rounded to 0 and gives me the wrong answer

  • 1
    Please see [Why JavaScript is Bad At Math](https://javascript.plainenglish.io/why-javascript-is-bad-at-math-9b8247640caa) – Can O' Spam Dec 06 '22 at 12:51

1 Answers1

0

The documentation for Number.prototype.toFixed() describes what's happening in this exact case: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

2.34.toFixed(1); // '2.3'
2.35.toFixed(1); // '2.4'; it rounds up
2.55.toFixed(1); // '2.5'
// it rounds down as it can't be represented exactly by a float and the
// closest representable float is lower
2.449999999999999999.toFixed(1); // '2.5'
// it rounds up as it's less than NUMBER.EPSILON away from 2.45.
// This literal actually encodes the same number value as 2.45
Heysunk
  • 71
  • 2