0

I have a math problem with PHP and I don't understand why this happens.

I use the following construct, and it worked well but I found a bug and don't know how to fix it.

$value1 = 0.07;
$value2 = 0.7;

$difference = $value2 - ($value1 * 10);
echo $difference;

If you use random values like $value1 = 0.5 and $value2 = 13, it works like it should. In this case, 0.7 - (0.07 * 10) = -1.11022302463E-16 and I don't understand why. If you use other values like $value1 = 0.5 and $value2 = 5, there's no problem even if the result should be 0 too.

Hopefully, somebody might know where's the problem and how to fix it.

best regards

L4rs
  • 3
  • 2
  • 3
    `$difference = $p2 - ($p1 * 10)` Where is `$p1` or `$p2` defined? The problem probably resolves around the fact that `$value1` and `$value2` are nowhere to be seen in `$difference`. –  Jul 02 '17 at 14:32
  • 2
    you should learn about `floats` and their internal representation. This is not unique to php , and you will find that kind of discrepancy in any system that has support for floating point operations. Deal with it. – YvesLeBorg Jul 02 '17 at 14:34
  • Consider checking out [this library](https://github.com/direvus/php-decimal) which may be useful in manipulating floating point numbers. – Blue Jul 02 '17 at 14:38
  • 1
    You can no more represent 0.1 exactly in binary than you can 1/3 in decimal. – duffymo Jul 02 '17 at 15:00

0 Answers0