1
Math.pow(3, -222)

gives 1.199724291183359e-106

 5 + Math.pow(3, -222)

gives 5 !

i have tried to use parseFloat() and also toPrecision() but nothing happened

mustafa mohamed
  • 135
  • 2
  • 6
  • 3
    Floating point numbers have limited ability to represent very large and very small values. – Pointy Dec 20 '19 at 19:40
  • 7
    `1.199724291183359e-106` is a *very small* number, not a "big" one. – jcalz Dec 20 '19 at 19:40
  • 4
    because`5 + Math.pow(3, -222)` simply can't be presented by one number.. – Liad Yogev Dec 20 '19 at 19:43
  • 2
    @LiadYogev It is not only a question of representing, small parts are just lost, if you will reduce 5 it will show you 0, not an original value – Dmitry Reutov Dec 20 '19 at 19:48
  • 1
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Heretic Monkey Dec 20 '19 at 19:48
  • I suggest that you peruse https://floating-point-gui.de/ which is a very gentle introduction into functioning of floating-point numbers, and their limitations. – 9000 Dec 20 '19 at 19:49
  • @DmitryReutov if it can't be represented as a number, how can you expect it to save it as a number? – Liad Yogev Dec 20 '19 at 19:49
  • Well, it doesn't seem there is anything "wrong" with the math used here, but if your float is so small JavaScript can not handle it properly, you may want to rework you project. I can't imagine any use case in which you couldn't just use a larger decimal. – Jacob Cafiero Dec 20 '19 at 19:50
  • @LiadYogev, data and view are different things, you can not say that something is impossible to keep in data, just make 1000000 size array for each digit and keep incomparable more small numbers than this – Dmitry Reutov Dec 20 '19 at 19:52

1 Answers1

3

This is because IEEE floats are very precise close to zero. The farther away from zero you get, the less precise you can be.

3^-222 is so small that, when added to 5, it is rounded down to zero.

5+3^-222 doesn't exist as a float, and is closer to 5 than it is the smallest number above 5, so it's rounded down to 5.

Brandon Dyer
  • 1,316
  • 12
  • 21