0
$j = 0.1 + 0.2;
$k = 15.27 - (50.39 - 35.12);

var_dump($j);  // outputs: 0.3
var_dump($k);  // outputs: -3.5527136788005E-15

Both $j and $k have precision loss in binary. But why are they displayed differently in PHP? $j seems to be rounded to one tenth, where $k is not. :/

Can someone explain?

Skylervich
  • 150
  • 1
  • 8
  • lol, my question is literally the opposite of the duplicate. – Skylervich Apr 17 '20 at 02:10
  • looking at you Jay – Skylervich Apr 17 '20 at 02:11
  • 1
    I do not know PHP’s rules specifically, but a common method of formatting floating-point numbers is: If the number is between .001 (or some similar threshold) and 1,000,000, then format it as a fixed-point number with a specific number of digits after the decimal point (sometimes with trailing zeros removed). Otherwise, display it in scientific format. Since your first result is very near .3, formatting it with six digits after the decimal point yields 0.300000, or 0.3. Since your second result is small, scientific notation is used. – Eric Postpischil Apr 17 '20 at 02:18
  • 1
    Also note that because the first result is “large,” the result is very near the result you would get from adding .1 and .2 with real-number arithmetic. So the error is very small compared to that and is not visible in the formatted number. The second result is small—the real-number result would be exactly zero, so the floating-point result is 100% error and so is entirely visible in the formatted number. – Eric Postpischil Apr 17 '20 at 02:20
  • Thanks for taking a look Eric. I think you're probably right. There is a "precision" setting in PHP. Its set to a magic number 14. I THINK it has something to do with what you're talkign about. I just can't get the math to work out. :( – Skylervich Apr 17 '20 at 02:23

0 Answers0