Search code examples
phpadditionsubtraction

Incorrect results obtained in simple arithmetic using php


Here is a simple PHP script:

<?php
  $a = 100;
  $b = 91.51;
  $c = 8.49;

  $d = $a - $b - $c;
  echo $d;
?>

It outputs -5.3290705182008E-15 which is ugly With minor change as follows:

  $d = $a - ($b + $c);
  echo $d;
?>

The output is 0 which is correct. Why is this happening?


Solution

  • Try to use number_format like this:

      $a = 100;
    
      $b = number_format(91.51, 0, ".", "." );
    
      $c = number_format(8.49, 0, ".", "." );
    
      $d = $a - $b - $c;
    
      echo $d;