1

I am having difficulty after doing some simple decimal math in PHP with values, not cross-footing and comparing as expected. So, I put together a simple test to show myself what is wrong but I continue to get unexpected results.

This example should test to FALSE but it doesn't, Why is that. What is going on with the decimal values that don't compare as expected? If I change the "!=" to a "<" it compares TRUE. Why is that? I have tried various combinations of not ==, !=, etc. but nothing seems to work as expected.

What is going on here?

$diff = 17466.47 - 8530.65;

If ($diff != 8935.82) { 
    Process as an error...
}
sajad abbasi
  • 1,988
  • 2
  • 22
  • 43
Jean J.
  • 11
  • 1
  • 1
    Starting point: read [What Every Programmer Should Know About Floating-Point Arithmetic](http://floating-point-gui.de/) – Mark Baker Sep 17 '17 at 11:46
  • Second, read the [PHP Docs on floating point numbers](http://php.net/manual/en/language.types.float.php) particularly the big warning message, and the section on how to [compare floating point values](http://php.net/manual/en/language.types.float.php#language.types.float.comparison) – Mark Baker Sep 17 '17 at 11:48
  • Thanks! Yes I did extensive reading on PHP and floating point numbers and eventually solved my issue by writing a simple function to change my decimal/float values to strings and compared those. Seems to work well for my simple case. I am however a bit shocked that such widely used language as PHP cannot natively do simple Monetary Dollars and Cents math without having these weird side-effects... Even the old dBase Language could do this easily... – Jean J. Sep 17 '17 at 19:14
  • You are aware that almost every modern programming language uses IEEE754 for floating point numbers, so this isn't restricted to PHP. Most do provide options for handling arbitrary precision, like PHP's [bcmath](http://php.net/manual/en/book.bc.php) or [gmp](http://php.net/manual/en/book.gmp.php) extensions, but there is inevitably a performance overhead.... personally I used COBOL a lot back in the day, which provided a bcd format for handling arbitrary precision decimals – Mark Baker Sep 17 '17 at 20:30
  • You can also use the [PHP Decimal](http://php-decimal.io) extension. – rtheunissen Nov 15 '18 at 23:01

0 Answers0