PHP uses integers for whole numbers and floating-point values for numbers with a fractional part. Counting products, calculating pages and displaying measurements all involve numbers, but they do not always need the same rules. A page count must round upward; a temperature may need one decimal place; an amount in cents should remain an exact integer whenever the business rule allows it.
This guide covers arithmetic and the most useful math functions, then explains numeric strings, rounding and floating-point limits. The examples use small values so you can check the answers by hand. Read PHP variables first, and remember that input from a form generally starts as text even when the visitor typed digits.
Integers, floats and arithmetic
An int stores a whole number within the range supported by the platform. Most modern installations use 64-bit integers, but portable code should not hardcode that assumption for very large identifiers. PHP_INT_MAX and PHP_INT_SIZE describe the running environment. Arithmetic that exceeds the integer range can produce a float, which may no longer represent every integer exactly.
A float stores an approximate number using binary floating-point representation. Decimal fractions such as one tenth often have no exact binary representation. That is normal computer behavior, not a broken addition operator. Use floats for measurements when a small tolerance is acceptable. For exact currency totals, integer minor units or an appropriate decimal library are better choices.
The arithmetic operators are +, -, *, /, % and **. Division usually gives the numeric quotient; intdiv() specifically requests an integer quotient. The remainder operator % works on integer values and is useful for divisibility and cycling through groups. Division by zero is an error, so validate a divisor before performing a calculation.
Choose a rounding rule before choosing a function
floor() rounds downward toward negative infinity. ceil() rounds upward toward positive infinity. That means floor(-2.3) is negative three and ceil(-2.3) is negative two. Neither function simply removes the fractional part. Casting to int truncates toward zero, so it answers a different question for negative values.
round() rounds to a requested number of decimal places. At halfway values, the rounding mode determines which direction is chosen. PHP supports explicit rounding mode constants, and newer versions also provide a rounding mode enum. Specify the rule when the result affects invoices, statistics or another domain with a defined rounding policy. Avoid relying on a vague phrase such as normal rounding.
Formatting is a separate step. number_format() returns display text with the chosen decimals and separators. That text should not become the input to another calculation, because formatting may add commas or other characters. Keep a numeric value for arithmetic and derive a formatted string only when presenting the result.
Numeric strings and validation
is_numeric() recognizes values PHP considers numeric, including forms such as scientific notation. It does not tell you whether the value is an allowed quantity, a nonnegative amount or an identifier with a specific format. An order quantity might require a validated integer between one and fifty, even though 1.5 is numeric.
Do not use a cast as your only input validation. Casting text to an integer can lose information and accept input you meant to reject. Validate the expected format and range, then convert. If a form allows decimal amounts, decide which decimal separator and number of places are accepted. Locale-formatted text such as 1,200.50 should not be passed directly into arithmetic.
Comparing floating-point values with === can be surprising after calculations. Use an appropriate tolerance for measurements, such as checking whether the absolute difference is below a small threshold. Choose that threshold from the application's accuracy needs. A tolerance suitable for a screen animation would be inappropriate for an exact ledger balance.
PHP Numbers and Math Functions Examples
Each example shows the code, the output it produces and what each part does.
Whole-number division and remainders
Three boxes can be filled completely, with two items left over. That differs from asking for the number of boxes needed to hold everything, which requires rounding upward. Parentheses around the remainder and exponent expressions make the output concatenation easy to read. abs() returns the distance from zero, so the negative sign disappears.
<?php
$items = 17;
$boxSize = 5;
echo intdiv($items, $boxSize) . PHP_EOL;
echo ($items % $boxSize) . PHP_EOL;
echo (2 ** 4) . PHP_EOL;
echo abs(-8) . PHP_EOL;3
2
16
8Compare rounding with display formatting
The final line has two visible decimal places because it is formatted text. A numeric float does not preserve a display instruction saying always show two decimals. Keep that distinction in mind when an API returns numbers and a template decides how many decimal places to show.
<?php
$measurement = 12.345;
echo floor($measurement) . PHP_EOL;
echo ceil($measurement) . PHP_EOL;
echo round($measurement, 2, PHP_ROUND_HALF_UP) . PHP_EOL;
echo number_format(12.3, 2, '.', '') . PHP_EOL;12
13
12.35
12.30Common PHP Numbers and Math Functions Mistakes
Using random numbers or min/max without checking purpose
min() and max() find the smallest and largest values, but mixed types can produce comparisons you did not intend. Normalize and validate a collection before comparing numeric values. sqrt() and logarithm functions also have mathematical domain restrictions; passing an invalid domain can yield a nonfinite result rather than a usable measurement.
For security-sensitive random integers, use random_int() rather than a simulation-oriented pseudorandom function. A password reset token needs secure randomness and sufficient entropy; a random integer example is not a complete token design. Consult the PHP math reference for exact signatures, and the round() documentation for version-specific modes and error behavior.
PHP Numbers and Math Functions in Real Projects
Practical task: boxes needed for an order
Calculate how many boxes are needed for thirty-two items when each box holds six items. The input values are already trusted integers. Reject a nonpositive capacity, divide the count by capacity, and round upward. Then calculate the unused spaces. This task separates capacity planning from integer division: the partially filled final box still counts as a box.
<?php
$items = 32;
$capacity = 6;
if ($capacity <= 0 || $items < 0) {
throw new InvalidArgumentException('Invalid box calculation');
}
$boxes = (int) ceil($items / $capacity);
$unused = $boxes * $capacity - $items;
echo 'Boxes: ' . $boxes . PHP_EOL;
echo 'Unused spaces: ' . $unused . PHP_EOL;Boxes: 6
Unused spaces: 4Five boxes hold only thirty items, so the solution needs six. Those boxes provide thirty-six spaces, leaving four unused. Try zero items and a count exactly divisible by six. In an input-driven application, validate the original request before this calculation; the checks here protect the arithmetic rule but do not parse untrusted text.
PHP Numbers and Math Functions FAQ
Why does decimal addition sometimes look slightly wrong?
Many decimal fractions are approximations in binary floating point. Format the display appropriately, and choose exact integer or decimal arithmetic when exact decimal values matter.
Does floor() return an integer type?
It returns a float holding a whole-number value. Cast only when an integer is appropriate and the value is within range.
Is is_numeric() enough for a quantity field?
No. It checks numeric form, not the business rule. A quantity may need to be a bounded positive integer.
Can I calculate with number_format() output?
Avoid it. The result is presentation text. Keep the original number for calculations and format at the output boundary.
PHP Numbers and Math Functions Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
An application stores a price as integer cents. Which value represents 12.50 units?
PHP Numbers and Math Functions Quiz
2 questions to check what you learned.
Which function counts the boxes required when division leaves a fraction?
- ceil()
- floor()
- abs()
What does intdiv(17, 5) return?
- 3.4
- 3
- 2