PHP Reference ยท Types and Type Handling
The PHP float type
Reference for the PHP float type: literals, IEEE 754 precision, comparing with a tolerance, NAN and INF, rounding, formatting and float-to-int conversion.
A float (also called double) is a 64-bit IEEE 754 floating-point number. It covers roughly 15 to 17 significant decimal digits and a huge range, about 1.8e308 at the top. Many decimal fractions, such as 0.1, cannot be stored exactly in binary, so small errors appear in calculations.
Treat floats as approximations. Round for display, compare with a tolerance, and keep money in integer cents or in a decimal library or bcmath.
$price = 19.99; $big = 1.5e6; // 1500000.0 $small = 2.5E-3; // 0.0025
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
$a = 1.234; $b = 1.2e3; $c = 7E-10; $d = 1_000.5; $e = (float) $value; // or (double), floatval($value)
Constants: PHP_FLOAT_EPSILON (smallest difference from 1.0), PHP_FLOAT_MAX, PHP_FLOAT_MIN, PHP_FLOAT_DIG, plus INF and NAN.
Usage notes
- Never compare computed floats with
==. Useabs($a - $b) < $epsilonwith a tolerance that fits your data.PHP_FLOAT_EPSILONis the right scale for numbers near 1 only. NANis not equal to anything, not even itself. Test withis_nan().INFcomes from overflow andfdiv(1, 0);1 / 0throwsDivisionByZeroError.- Display uses
precision/serialize_precision.echo 0.1 + 0.2prints0.3becauseechorounds to 14 digits (theprecisionsetting), whilevar_dumpandjson_encodeprint the shortest string that round-trips (0.30000000000000004). round()rounds half away from zero (round(2.5)is3,round(-2.5)is-3). Because the stored value is only an approximation of the decimal you typed, rounding ties at many digits can still disagree with your expectation. For money use integers.- Float to int conversion truncates and is meaningless for
NAN,INFor values beyond the int range. Deprecations apply when a float with a fractional part is used where an int is required (array keys,%, bit operations). - Integers beyond 2^53 lose exactness as floats. Keep IDs as ints or strings.
- Formatting:
number_format(),sprintf("%.2f")andNumberFormatter(intl) are for output; they return strings. - Locale-independent. Since PHP 8, float-to-string conversion no longer depends on the locale, so you always get a
.as decimal separator. %converts operands to int.7.5 % 2is1(with a deprecation notice, since the fraction is lost), and1 % 0.5throwsDivisionByZeroErrorbecause the divisor becomes0. Usefmod()for floats.