Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 147 ยท Data Types

Integers and Floats

Learn PHP numbers - int size and overflow, hex, octal and binary literals, 1_000_000 separators, float precision, intdiv, fdiv, modulo and numeric strings.

PHP has two number types. An integer (int) is a whole number like 42, -7 or 0. A float (also called a double) is a number with a fractional part or an exponent, like 3.14, -0.5 or 1.2e6. Prices, quantities, IDs, percentages and coordinates all end up as one of these two types, so it pays to know exactly how they behave.

The rules are mostly what you'd expect from a calculator, with a few important exceptions: integers have a maximum size, floats can't store most decimal fractions exactly, and strings that look like numbers are treated as numbers in arithmetic. This lesson covers all three, plus the integer literal formats, division and remainders, and how to check whether a value is numeric.

If you haven't yet, read Data Types first; it explains var_dump(), which this lesson uses to show both the type and the value of every result.

Integers

An integer literal is just digits, with an optional sign. Besides ordinary decimal numbers, PHP understands three other bases, and since PHP 7.4 you can put underscores between digits to make long numbers readable:

PHP Integer literals in four bases

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.

All five of the first values are the same number, 255, so var_dump() prints int(255) five times. The underscores in 8_100_000_000 are purely visual; PHP ignores them, and the value prints as int(8100000000). The prefixes are case-insensitive (0XFF works too), but lowercase is the common style.

A leading zero makes a number octal. $zip = 02134; stores 1116, not 2134, and 09 is a parse error because 9 isn't an octal digit. Write the explicit 0o prefix (PHP 8.1+) when you really want octal, such as file permissions (0o755), and keep things like ZIP codes and phone numbers in strings.

How big can an integer be?

PHP integers are signed and use the platform's native size. On every 64-bit system (which is practically all of them today), that's 8 bytes, giving a range of about ยฑ9.2 quintillion. PHP tells you the exact limits through constants. What happens when you go past the limit is unusual: PHP doesn't wrap around like C or throw an error. It quietly switches to a float.

PHP Integer limits and overflow

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.

The output:

TEXT
8 bytes
int(9223372036854775807)
int(-9223372036854775808)
float(9.223372036854776E+18)
bool(true)
int(4611686018427387904)
float(9.223372036854776E+18)

Adding 1 to PHP_INT_MAX gives a float, and that float can't tell the two numbers apart: $big == PHP_INT_MAX is true because both round to the same float. Once you've overflowed, you've lost precision. For most programs this never comes up, but it matters for very large IDs (some APIs send 64-bit IDs that you should keep as strings), factorials, and cryptography. For integers of any size, PHP has the gmp and bcmath extensions, introduced in Math Functions.

Floats

A float literal has a decimal point, an exponent, or both. Exponents use e (or E) and mean "times ten to the power of":

PHP
$pi = 3.14159;
$half = .5;           // allowed, but 0.5 is clearer
$distance = 1.5e3;    // 1500.0
$tiny = 2.5E-4;       // 0.00025
$rate = 1_000.25;     // separators work in floats too

PHP floats are 64-bit IEEE 754 numbers, the same format JavaScript, Python and Java's double use. They hold about 15 to 17 significant decimal digits (PHP_FLOAT_DIG is 15, the number of digits that always survive a round trip) and can reach roughly ยฑ1.8 ร— 10308.

Why 0.1 + 0.2 is not 0.3

Floats store numbers in binary. Just as 1/3 can't be written exactly in decimal (0.333...), most decimal fractions, including 0.1 and 0.2, can't be written exactly in binary. The computer stores the nearest value it can, and the tiny errors show up in arithmetic:

PHP Float precision in action

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.

You'll see:

TEXT
float(0.30000000000000004)
bool(false)
0.3
0.3
bool(true)
float(3.3333333333333335)
float(0.75)

Four lessons come out of this:

  1. Never compare floats with ==. Check whether the difference is smaller than a tolerance, as on line 10, or round both sides to the precision you care about.
  2. echo hides the noise; var_dump() shows it. Line 6 prints 0.3 because echo rounds floats to 14 significant digits. var_dump() shows the exact stored value. Don't let a clean-looking echo convince you the value is exact.
  3. Round when you display. round(), number_format() and printf('%.2f') give humans the precision they expect.
  4. Never store money in floats. Store whole cents as integers (1999 for 19.99) or use bcmath decimal strings. Values like 0.5 and 0.75 are exact in binary, which is why the last line prints cleanly, but you can't count on that for prices.

var_dump(), var_export() and json_encode() print the shortest decimal number that converts back to exactly the same float, so they show 0.30000000000000004. That's controlled by the serialize_precision setting (default -1, meaning "shortest exact"). echo, print and string conversion use the separate precision setting (default 14 significant digits), so echo 0.1 + 0.2 prints 0.3. When you're debugging a comparison that "should" be true, reach for var_dump().

Special float values: INF and NAN

Floats have values for "too big" and "not a number". INF is positive infinity, -INF negative infinity, and NAN is the result of undefined operations like 0/0. NAN is never equal to anything, not even itself, so test for these with functions:

PHP
$huge = 1e308 * 10;      // float(INF)
var_dump(is_infinite($huge));   // bool(true)
var_dump(is_nan(NAN));          // bool(true)
var_dump(NAN == NAN);           // bool(false)
var_dump(is_finite(42.0));      // bool(true)

Division, intdiv and fdiv

The / operator returns an int when both operands are integers and the result is a whole number, and a float otherwise. To get an integer quotient, use intdiv(), which truncates toward zero. Dividing by zero is not a warning in PHP 8: it throws a DivisionByZeroError, which stops your script unless you catch it. If you want IEEE behavior (infinity or NaN) instead, use fdiv() (PHP 8.0+).

PHP Dividing integers and floats

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.

The output:

TEXT
int(3)
float(3.5)
int(3)
int(-3)
int(3)
float(INF)
float(NAN)
Caught: Division by zero

try/catch is explained properly in Exceptions; for now, just know that it lets the script continue after an error.

The remainder operator %

% (modulo) gives the remainder of an integer division. It converts both operands to integers first, and the result takes the sign of the left operand: -7 % 3 is -1, and 7 % -3 is 1. % 0 throws DivisionByZeroError with the message Modulo by zero. For floats, use fmod(): fmod(7.5, 2) is 1.5.

The most common uses are checking for even numbers ($n % 2 === 0), doing something every Nth time ($i % 10 === 0), and wrapping around ($index % count($items)). You'll practice these in Arithmetic and Assignment Operators.

Converting between ints and floats

Mixing the two types in arithmetic produces a float: 2 + 1.5 is float(3.5), and even 2 + 1.0 is float(3). Converting a float to an int with (int) or intval() truncates toward zero; it doesn't round:

PHP Truncating and converting

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.

The first three lines give int(3), int(-3) and int(4): if you want rounding, round first, then cast. The last line converts a float that's far too large for an integer. The result is meaningless, and PHP 8.5 warns about it:

TEXT
Warning: The float 1.0E+20 is not representable as an int, cast occurred in main.php on line 10
int(7766279631452241920)

NAN and INF produce the same warning (and become 0). The full set of conversion rules is in Type Juggling and Casting.

Numeric strings

Data from forms, URLs, files and many databases arrives as strings, even when it's a number. PHP lets you use such strings directly in arithmetic. A string is numeric if it contains an integer or float, optionally with whitespace before or after it: "42", " 3.5", "1e3", "-7 ".

  • A fully numeric string is converted silently: "10" + 5 is int(15), "1.5" * 2 is float(3).
  • A leading-numeric string such as "42abc" is converted using its leading number, but with a warning: A non-numeric value encountered.
  • A non-numeric string such as "abc" throws a TypeError in arithmetic since PHP 8.0. (PHP 7 silently treated it as 0.)
PHP Strings in arithmetic

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.

Read the output from top to bottom: four clean conversions, then is_numeric() returns true three times and false three times (hex strings like '0x1A' are not numeric), then the warning for '42abc' along with int(43), and finally the script stops on line 11 with a fatal error, on purpose:

TEXT
Fatal error: Uncaught TypeError: Unsupported operand types: string + int in main.php:11

That last error is a good thing. A typo like $total = $qty + 'abc' used to produce a silent wrong answer; now it fails loudly. The practical rule for input you don't control: check it first with is_numeric(), or better, validate and convert it with filter_var($input, FILTER_VALIDATE_INT) as shown in Form Validation. Never let a raw string flow straight into a calculation.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does var_dump(8 / 4); print?

    When both operands are integers and the division is exact, / returns an int. 7 / 2 would return float(3.5).
  2. 2. What is var_dump(PHP_INT_MAX + 1); on a 64-bit system?

    PHP integers never wrap around. When a result is too big for an int, PHP switches to a float, losing exact precision.
  3. 3. What does var_dump(0.1 + 0.2 == 0.3); print?

    0.1 and 0.2 can't be stored exactly in binary, so their sum is 0.30000000000000004. Compare floats with a tolerance or round them first.
  4. 4. What is the value of 017?

    A leading zero makes an integer literal octal, and octal 17 is 1ร—8 + 7 = 15. Since PHP 8.1 you can write 0o17 to make the intent clear.
  5. 5. What happens with $x = 'abc' * 2; in PHP 8?

    Since PHP 8.0, arithmetic on a non-numeric string throws TypeError (Unsupported operand types). A leading-numeric string like '3abc' only gives a warning.

Summary

  • int holds whole numbers, 64-bit on modern systems: PHP_INT_MAX is 9223372036854775807. Results beyond that silently become floats.
  • Integer literals can be decimal, hex (0xFF), octal (0o17, PHP 8.1+, or a leading 0) and binary (0b1010), with _ separators (PHP 7.4+).
  • Floats are 64-bit IEEE 754 numbers. Most decimal fractions aren't exact, so never compare floats with == and never store money in them.
  • / returns an int only for exact integer division; intdiv() truncates; fdiv() returns INF/NAN; / 0 and % 0 throw DivisionByZeroError.
  • % keeps the sign of the left operand; use fmod() for floats.
  • (int) truncates toward zero. Round first if you want rounding.
  • Numeric strings work in arithmetic; leading-numeric strings warn; non-numeric strings throw TypeError. Use is_numeric() or filter_var() to check input.

Next: Booleans and null