W3docs

PHP Numbers: A Comprehensive Guide

Learn how PHP handles integers and floats, arithmetic, integer division, float-precision gotchas, math functions, and number formatting — with examples.

Numbers are at the core of almost every PHP program — counting items, computing prices, measuring sizes. This chapter covers the two numeric types PHP offers, how to write numbers in different notations, the arithmetic and math functions you'll use most, the float-precision trap that catches every developer at least once, and how to format and validate numbers safely.

Understanding PHP Numeric Data Types

PHP has two numeric data types:

  • int (integer) — a whole number with no fractional part, such as 42 or -7.
  • float (floating-point, also called double) — a number with a fractional part, such as 3.14 or -0.5.

PHP is loosely typed, so you never declare the type. PHP picks int or float automatically based on the literal you write and the operations you perform. You can check the type at runtime with gettype() or var_dump().

The size of an integer is platform-dependent. On a 64-bit system (the common case today) an integer ranges from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807; on a 32-bit system the range is -2,147,483,648 to 2,147,483,647. The exact limit is available as the constant PHP_INT_MAX. When a calculation exceeds it, PHP silently converts the result to a float rather than overflowing — so very large integers can lose precision.

Writing Number Literals

You are not limited to plain decimal notation. PHP understands several bases, plus underscores for readability:

<?php
$dec = 42;        // decimal integer
$float = 3.14;    // floating-point
$hex = 0x1A;      // hexadecimal, equals 26
$oct = 0o17;      // octal (PHP 8.1+ "0o" prefix), equals 15
$bin = 0b101;     // binary, equals 5
$big = 1_000_000; // underscores are ignored (PHP 7.4+), equals 1000000

echo $hex, "\n";  // 26
echo $oct, "\n";  // 15
echo $bin, "\n";  // 5
echo $big, "\n";  // 1000000

var_dump($dec);   // int(42)
var_dump($float); // float(3.14)
?>

The underscores are purely cosmetic — PHP ignores them — but they make long numbers like 1_000_000 far easier to read. See the PHP Data Types chapter for how these fit alongside strings, booleans, and arrays.

Arithmetic Operations in PHP

PHP supports the standard arithmetic operators: addition (+), subtraction (-), multiplication (*), division (/), modulus (%), and exponentiation (**). The full set is covered in PHP Operators. Here is each of the core operations in action:

<?php
$num1 = 10;
$num2 = 5;

// Addition
$result = $num1 + $num2;
echo "\$num1 + \$num2 = ";
echo $result; // 15

// Subtraction
$result = $num1 - $num2;
echo "\n\$num1 - \$num2 = ";
echo $result; // 5

// Multiplication
$result = $num1 * $num2;
echo "\n\$num1 * \$num2 = ";
echo $result; // 50

// Division
$result = $num1 / $num2;
echo "\n\$num1 / \$num2 = ";
echo $result; // 2

// Modulus
$result = $num1 % $num2;
echo "\n\$num1 % \$num2 = ";
echo $result; // 0
?>

Division, Integer Division, and Modulus

Division in PHP has a subtlety worth knowing. The / operator returns a float whenever the result is not a whole number, and an int when the operands divide evenly. For a result that is always an integer, use intdiv(). For the remainder, % works on integers and fmod() works on floats:

<?php
var_dump(10 / 4);        // float(2.5)  — not evenly divisible
var_dump(10 / 5);        // int(2)      — evenly divisible
var_dump(intdiv(10, 4)); // int(2)      — integer division, remainder dropped
var_dump(10 % 4);        // int(2)      — modulus (remainder)
var_dump(fmod(10.5, 3)); // float(1.5)  — floating-point remainder
?>

Dividing by zero throws a DivisionByZeroError in PHP 8 and later, so guard the divisor before dividing if it could be 0.

Floating-Point Precision

Floats cannot represent every decimal value exactly, because they are stored in binary. This leads to a classic surprise:

<?php
var_dump(0.1 + 0.2 === 0.3); // bool(false) — not exactly equal!

// Compare floats with a small tolerance instead:
$epsilon = 1e-9;
var_dump(abs((0.1 + 0.2) - 0.3) < $epsilon); // bool(true)
?>

0.1 + 0.2 is actually 0.30000000000000004, so the strict === comparison fails even though echo rounds it to 0.3 for display. The rule of thumb: never compare floats with == or === — check whether their difference is within a tiny tolerance (an epsilon). For money and other exact-decimal work, store values as integer cents or use the BCMath / GMP extensions.

Advanced Mathematical Functions in PHP

Beyond the operators, PHP ships a rich set of built-in math functions. The most common ones are:

  • abs() — the absolute (non-negative) value of a number
  • ceil() — rounds up to the nearest integer
  • floor() — rounds down to the nearest integer
  • round() — rounds to the nearest integer, or to a given number of decimals
  • sqrt() — the square root of a number
  • pow() — raises a number to a power (same as the ** operator)
  • max() / min() — the largest / smallest of the supplied values
  • rand() / random_int() — a random number (random_int() is cryptographically secure)

The complete list lives in the PHP Math reference. Here is a selection in use:

<?php
$num1 = -10;
$num2 = 2.7;

// Absolute value
$result = abs($num1);
echo "abs(\$num1) = ";
echo $result  . "\n"; // 10

// Round up
$result = ceil($num2);
echo "ceil(\$num2) = ";
echo $result . "\n"; // 3

// Round down
$result = floor($num2);
echo "floor(\$num2) = ";
echo $result . "\n"; // 2

// Square root
$result = sqrt(9);
echo "sqrt(9) = ";
echo $result . "\n";  // 3

// Raise to power
$result = pow(2, 3);
echo "pow(2, 3) = ";
echo $result; // 8
?>

Formatting Numbers for Display

Raw numbers rarely look good on a page. number_format() adds thousands separators and fixes the number of decimal places, and round() controls precision in calculations:

<?php
echo number_format(1234567.891, 2), "\n";          // 1,234,567.89
echo number_format(1234567.891, 2, '.', ' '), "\n"; // 1 234 567.89 (custom separators)
echo round(3.14159, 2), "\n";                       // 3.14
?>

The second and following arguments of number_format() let you set the decimal count and choose the decimal and thousands separators — handy for locale-specific output.

Checking and Converting Numeric Values

When data arrives from forms, URLs, or files, it is text. Validate it before doing arithmetic. is_int() and is_float() check the actual type, while is_numeric() checks whether a string looks like a number. To convert, cast with (int) / (float) or use floatval():

<?php
var_dump(is_int(42));          // bool(true)
var_dump(is_float(3.14));      // bool(true)
var_dump(is_numeric("123"));   // bool(true)  — numeric string
var_dump(is_numeric("12abc")); // bool(false) — not numeric

echo (int) "42px", "\n";       // 42  — leading digits are kept, the rest dropped
echo PHP_INT_MAX, "\n";        // 9223372036854775807 on a 64-bit system
?>

Related type guards have their own chapters: is_int() and is_float().

Conclusion

In conclusion, numbers play a crucial role in PHP programming and it is important to have a solid understanding of how to work with them. Whether you are performing basic arithmetic operations or advanced mathematical functions, PHP provides a variety of tools to help you get the job done. With the knowledge you have gained from this article, you are now equipped to tackle any number-related task in your PHP projects.

Practice

Practice
Which of the following are correct with regard to PHP numbers?
Which of the following are correct with regard to PHP numbers?
Was this page helpful?