使用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?

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;

Floating point maths is actually very inaccurate. It's a "best guess" value ;)

In floating point (single precision) 100 - 91.51 is not 8.49 as you would expect, but 8.4899978638 since the value 8.49 cannot be exactly expressed in floating point. With double precision it gets better, as it equates to 8.48999999999999488409 which is a little closer. Still not exact though.

Take the following code example:

echo (100 - 91.51) . "
";
echo number_format(100 - 91.51, 20) . "
";

The output of that you would expect to be

8.49
8.49000000000000000000

But in fact it is:

8.49
8.48999999999999488409

It defaults to rounding to 2 decimal places for printing floating point values.

Floating point is very much a trade-off. It is a numerical representation system that provides increased resolution and range at the cost of accuracy. For accuracy, but with limited resolution and range, fixed point arithmetic is often used. For instance, if you were storing voltage values between 0V and 5V and you wanted precise measurements at 1µV resolution (i.e., 0.000001V divisions) you may choose to instead represent your voltages in microvolts not volts, so a value of 100000 would actually be 0.1V, and 3827498 would be 3.827498 volts. The mathematics at your prescribed resolution become precise, however you lack the ability to then represent 287x1036V without having massive variables to store the value.