0

I have an issue about toFixed method.

When i run this code 1.535.toFixed(2) The result is 1.53. But when i run this code 2.535.toFixed(2) The result is 2.54 so it rounded. How it is possible?

1.535.toFixed(2) this result should be 1.54 not 1.53

  • https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript JavaScript has always had issues with rounding floating point numbers, so this could be one such case where the compiler struggles to guess which way to round. – Archigan Oct 26 '22 at 16:38
  • That's because `(2.535).toFixed(16) === '2.53500000000000014'` Floating points are not exact. – Ruan Mendes Oct 26 '22 at 16:43
  • Alternatively, "Floating point numbers cannot represent all decimals precisely in binary. This can lead to unexpected results, such as `0.1 + 0.2 === 0.3` returning `false`. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed – Archigan Oct 26 '22 at 16:44
  • @Archigan Your first statement is misleading. The "problem" is way broader, it doesn't apply to JavaScript only; any language that uses IEEE floating points has that problem. https://timothybramlett.com/floating-point-imprecision.html – Ruan Mendes Oct 26 '22 at 17:11
  • I really only use TS/JS, so I was not aware that other languages had this issue as well, though thinking about it now it makes sense. – Archigan Oct 26 '22 at 17:16

0 Answers0