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

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.
$float0 = acos(2);
if($float0 == $float0)
    echo "True\r\n";         // result: FALSE
    echo "$float0\r\n";
  • INF
    Constant INF represents a number which is beyond the representable range in floating point calculations.
$float0 = 1.8E+309;
echo "$float0";