Floating Point Numbers


Floating point numbers can be specified using any of the following syntaxes:

$float0 = 3.14;            // 3.14
$float1 = 3.14e3;          // 3140
$float2 = 3.14E-3;         // 0.00314

E3 (e3) above means multiplication by 1000 which is 10 cubed. E-3 (e-3) means multiplication by 1/1000 which is reciprocal number of 10 cubed.

To explicitly convert a value to floating point number, use the (float) casts and this is case-insensitive.

$a = 0.1 / 0.3;
printf("%.20e\r\n", $a);   // print $a down to 20 places of decimals
[result]  
3.33333333333333370341e-1

As you can see the result above, the value does not correct down to fifteen places of decimals. Because of these limitations, it is better not to use direct comparing operation of floating point numbers.

  • NAN
    Some numeric operations can result in a value represented by the constant NAN. This result represents an undefined or unpresentable value in floating point calculations. Any loose or strict comparisons of this value against any other value, including itself, will have a result of FALSE.
<?php
$float0 = acos(2);
if($float0 == $float0)
    echo "True\r\n";         // result: FALSE
else
    echo "$float0\r\n";
?>
[result]  
NAN
  • INF
    Constant INF represents a number which is beyond the representable range in floating point calculations.
<?php
$float0 = 1.8E+309;
echo "$float0";
?>
[result]  
INF