float

float — Floating-point number.

Floating point numbers (also known as "floats", "doubles", or "real numbers") .

<?php
$a = 1.234; 
$b = 1.2e3; 
$c = 7E-10;
?>

Some references to the type "double" may remain in the manual. Consider double the same as float; the two names exist only for historic reasons.

The size of a float is platform-dependent, although a maximum of approximately 1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).

Syntax

LNUM          [0-9]+
DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})

Floating point precision

  • Floating point numbers have limited precision.
  • It depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16.
  • Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.
  • Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa.
  • Floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....
  • Never trust floating number results to the last digit, and do not compare floating point numbers directly for equality.

Comparing floats

<?php
$a = 1.23456789;
$b = 1.23456780;
$epsilon = 0.00001;

if(abs($a-$b) < $epsilon) {
    echo "true";
}
?>

Testing floating point values for equality is problematic, due to the way that they are represented internally.

To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.

float — Structure map

Clickable & Draggable!

float — Related pages: