2

I found out recently that my code is generating negative zeroes. And this is my very first time encountering this scenario since 3 years ago.

The code was something like this:

$x =  "300.20";
$y =  ("300.10" + "0.10" + "0.00") - "0.00";
$z =  $x - $y;

The $x returns string, $y and $z return float. If you run this codes, $z's value is -5.6843418860808E-14, using number_format it will become -0.00.

Also, $y's value is 300.20 but it is not equal to 300.20 when comparing. Exactly same value but not equal.

My solution is to convert $y to string: $z = $x - strval($y); but the question is why is this happening?

Same output in PHP5 and PHP7

Shiz
  • 695
  • 10
  • 27
  • 2
    `float` number problem is all the same in all languages. see this: https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript . The "300.20", "300.10" and "0.10" are float numbers with precision problem – shawn Oct 01 '19 at 05:40
  • 1
    _Side note:_ When working with numbers, there's no reason to quote the values. Just use them as is: `$x = 300.20;` etc. – M. Eriksson Oct 01 '19 at 06:05
  • @MagnusEriksson those values are generated from database, which I don't have the power to change that datatype. but can only converted via PHP – Shiz Oct 01 '19 at 06:18
  • @ADyson you said "in the code above", and I said "The code was **something** like this:". because the real code is `$row['AMT']` generated from mysql query, I just represent the code something like that for better understanding. – Shiz Oct 01 '19 at 07:14

0 Answers0