Explain it simply
Explain it simply
In PHP you meet two kinds of numbers every day. An int is a whole number such as 15000, and a float is a decimal number such as 0.10. Prices, quantities, discounts, scores and ages all fit one of these two.
The surprising part is that floats store decimals as an approximation in binary, so some numbers cannot be stored exactly. That is why 0.1 + 0.2 is not exactly 0.3. Once you understand this, you can avoid the "off by a tiny amount" bugs that hit money calculations.
Problem → Why → Solution
The problem: the total is off by one
A shop multiplies the price 19.99 by 100 to store it in cents. The result should be 1999, but after an (int) cast it becomes 1998. That is one cent lost per customer, and over hundreds of orders it becomes a gap that is hard to trace.
<?php
$price = 19.99;
$cents = (int) ($price * 100);
echo $cents . PHP_EOL; // 1998, not 1999
$total = 0.1 + 0.2;
if ($total == 0.3) {
echo "equal";
} else {
echo "not equal"; // this branch runs
}Why is it not 1999?
19.99 cannot be stored exactly as a binary float, so 19.99 * 100 is really 1998.9999999999998. An (int) cast simply chops off the decimals without rounding, which leaves 1998. So never compare floats with ==, and either avoid floats for money or round() before converting to an int.
Core concept: int, float and numeric strings
PHP has two number types you will use daily. An int is a whole number; on a 64-bit build it ranges from -9223372036854775808 to 9223372036854775807 (PHP_INT_MIN and PHP_INT_MAX). A float is a decimal number stored in the IEEE 754 double format, the same format JavaScript and many other languages use. Literals like 15000 are ints; 0.10 and 1.5e3 are floats. var_dump() shows the exact type, while echo shows only the value.
The arithmetic operators keep or change the type. int + int stays int; as soon as a float is involved, the answer is a float. The / operator returns an int only when the division is exact (8 / 2 is int 4) and a float otherwise (7 / 2 is float 3.5). When you want whole-number division, use intdiv(). The % operator works on integers and its result takes the sign of the left operand, so -7 % 3 is -1. ** raises to a power.
Two traps need respect. First, int overflow: when an int result no longer fits, PHP silently converts it to a float, so PHP_INT_MAX + 1 becomes 9.223372036854776E+18 and you lose exactness. Second, float precision: 0.1 and 0.2 cannot be stored exactly in binary, so 0.1 + 0.2 is 0.30000000000000004 and == 0.3 is false. Never compare floats with ==; compare the difference with a tolerance, or avoid floats for money altogether by keeping amounts as whole integers of the smallest unit.
Numbers also arrive as strings: query strings, form fields and CSV files always deliver text. PHP 8 defines numeric strings clearly. A string such as "15", "1.5", " 15" or "15 " is numeric and works in arithmetic. A leading-numeric string like "12abc" is used as 12 but raises a warning. A non-numeric string such as "abc" throws a TypeError in arithmetic. Validate with is_numeric() or filter_var() before you calculate.
- Every value is an int or a float
- The operator looks at both operand types
- The result is an int, a float or an error
- Round and format only when displaying
Do not chop decimals while calculating; use round() and number_format() only at the display step.
General pattern
<?php
$whole = 42; // int
$decimal = 4.2; // float
$result = $a + $b; // + - * keep int, or become float
$quotient = intdiv($a, $b); // whole-number division
$remainder = $a % $b; // sign follows $a
$power = $a ** $b;
$shown = number_format($decimal, 2); // format only for display
var_dump($whole); // int(42) shows the typeA literal with a decimal point is a float, otherwise it is an int. var_dump() prints both the type and the value, so use it first whenever a result surprises you.
Example: a price with a discount
This example computes a discount on an int price with a float rate and checks what type the answer has. At the end, notice that comparing 0.1 + 0.2 with 0.3 gives false.
<?php
$price = 15000;
$discount = 0.10;
$finalPrice = $price - ($price * $discount);
var_dump($price);
var_dump($finalPrice);
echo "Final price: " . $finalPrice . " MMK" . PHP_EOL;
var_dump(is_numeric($finalPrice));
var_dump(0.1 + 0.2 == 0.3);Code breakdown
- Line 2
$price = 15000;No decimal point, so this is an int. var_dump($price) shows int(15000).
- Line 3
$discount = 0.10;A decimal point makes it a float. 0.10 is how we write 10%.
- Line 4
$finalPrice = $price - ($price * $discount);int * float is a float, so the whole result is a float. The value is 13500, but its type is float(13500).
- Line 7
echo "Final price: " . $finalPrice . " MMK" . PHP_EOL;Joining a float to a string prints 13500, not 13500.0, because echo shows decimals only when they are needed.
- Line 8
var_dump(is_numeric($finalPrice));is_numeric() returns true for ints, floats and numeric strings, so this prints bool(true).
- Line 9
var_dump(0.1 + 0.2 == 0.3);The left side is really 0.30000000000000004, so this prints bool(false). That is the float comparison trap in one line.
int(15000)
float(13500)
Final price: 13500 MMK
bool(true)
bool(false)Division, remainder and overflow
When you divide two integers, decide what you want. / gives the decimal answer, intdiv() gives the whole part (truncating toward zero) and % gives the remainder. Dividing by zero throws a DivisionByZeroError, so check the divisor first. Overflow, on the other hand, raises no error at all; the value just becomes a float.
<?php
var_dump(7 / 2); // float(3.5)
var_dump(8 / 2); // int(4): an exact division stays an int
var_dump(intdiv(7, 2)); // int(3)
var_dump(7 % 3); // int(1)
var_dump(-7 % 3); // int(-1): the sign follows the left operand
var_dump(fmod(7.5, 2)); // float(1.5): remainder for floats
var_dump(2 ** 10); // int(1024)
var_dump(2 ** -1); // float(0.5)
var_dump(PHP_INT_MAX + 1); // float(9.223372036854776E+18)
try {
echo intdiv(1, 0);
} catch (DivisionByZeroError $e) {
echo "Error: " . $e->getMessage() . PHP_EOL;
}Float precision and rounding
echo and var_dump() display floats differently. echo uses the precision setting (14 significant digits by default), so you see 0.3, while var_dump() shows the real stored value. The value is the same either way. round() sends a .5 away from zero, so round(2.5) is 3 and round(-2.5) is -3. The second argument is the number of decimals, and a negative number rounds to tens, hundreds and so on.
<?php
$sum = 0.1 + 0.2;
echo $sum . PHP_EOL; // 0.3
var_dump($sum); // float(0.30000000000000004)
var_dump($sum == 0.3); // bool(false)
var_dump(abs($sum - 0.3) < PHP_FLOAT_EPSILON); // bool(true)
echo round(2.5) . " " . round(3.5) . " " . round(-2.5) . PHP_EOL;
echo round(1234.5678, 2) . " " . round(1234.5678, -2) . PHP_EOL;
echo floor(-1.5) . " " . ceil(-1.5) . PHP_EOL;
echo number_format(1234.5678, 2) . PHP_EOL;For money
For money, whole integers are the simplest solution: store 1999 cents and format it as 19.99 only for display. For exact decimal arithmetic, look at the BCMath extension.
Numeric strings and form input
Values from users are always strings, so a bare (int) cast quietly turns "abc" into 0 and "12abc" into 12 without any complaint. filter_var() with FILTER_VALIDATE_INT returns the integer only when the text is a valid one and false otherwise, so you can show an error message.
<?php
var_dump("5" + "10"); // int(15)
var_dump("1.5" + 1); // float(2.5)
var_dump(" 12" + 1); // int(13): leading space is allowed
var_dump("12 " + 1); // int(13): trailing space is allowed in PHP 8
var_dump(is_numeric("12abc"), is_numeric("1e3"), is_numeric(""));
var_dump((int) "12abc"); // int(12): stops at the first bad character
var_dump((int) "abc"); // int(0)
var_dump(filter_var("12", FILTER_VALIDATE_INT)); // int(12)
var_dump(filter_var("12abc", FILTER_VALIDATE_INT)); // bool(false)
try {
echo "abc" * 2;
} catch (TypeError $e) {
echo get_class($e) . ": " . $e->getMessage() . PHP_EOL;
}In real projects
Where this shows up in real projects
Every online shop calculates prices, discounts, taxes and shipping fees. The float problem there starts as a small off-by-a-cent error and can end as an accounting report that does not add up, which is why storing money as whole integers is such a common practice.
Database drivers often return DECIMAL columns as strings, so remember to convert before calculating. Pagination divides the total row count by the page size and rounds up with ceil(); since / returns a float there, cast the page count back to an int. Validate a quantity from a form with filter_var() before comparing it with stock. For percentages, round() and number_format() belong at the display step, not in the middle of the calculation.
Common mistakes
Common mistakes
1. Comparing floats with ==
if ($total == 0.3) is false when $total is 0.1 + 0.2, so the "equal" branch never runs. Compare with a tolerance such as abs($a - $b) < 0.00001, or convert the values to integers first.
2. Using an (int) cast instead of round()
(int) (19.99 * 100) gives 1998, while (int) round(19.99 * 100) gives 1999. A cast chops the decimals off; round() picks the nearest whole number. Always round() before turning money into an int.
3. Casting user input without validating it
$qty = (int) $_POST['qty']; silently accepts "abc" as 0 and "12abc" as 12. filter_var($input, FILTER_VALIDATE_INT) returns false for bad input, so you can show an error and stop.
4. Expecting / to return an integer
$pages = $total / $perPage; gives float(2.5) for 25 / 10, and using that as an array index triggers a deprecation message. Use ceil() or intdiv() and keep the result an int.
Best practices
Best practices
- Store money as whole integers of the smallest unit and format it with number_format() only when you display it.
- Write every float comparison with a tolerance, and use intdiv() when you want the whole-number part of a division.
- Validate numbers from a form with is_numeric() or filter_var() before calculating, and use var_dump() to inspect doubtful values.
Mini challenge
Mini challenge: an invoice in cents
Calculate an invoice using integer cents only. Write one function that applies a percentage discount without floats and one that shows cents as 59.97.
- percentOf(int $cents, int $percent): int — compute the percentage with integers only (intdiv) and round a .5 up
- formatCents(int $cents): string — use sprintf() to return something like "59.97"; negative values must work too
- Make a subtotal of 3 items at 1999 cents, apply a 15% discount and print the total
- Do not use a float anywhere in this solution
<?php
function percentOf(int $cents, int $percent): int
{
// TODO: integer-only percentage; add 50 before intdiv(..., 100) to round half up
}
function formatCents(int $cents): string
{
// TODO: keep the sign, then combine intdiv($cents, 100) and $cents % 100
// with sprintf() so that 5 cents becomes "0.05"
}
// TODO: subtotal = 3 x 1999 cents, discount = percentOf(subtotal, 15), total
// TODO: echo each line with formatCents()Expected: Subtotal: 59.97 Discount: 9.00 Total: 50.97 Refund: -9.00
Show hint
sprintf('%d.%02d', $whole, $part) pads the remaining cents to two digits. For negatives, keep the sign aside and work with abs().
Show solution
<?php
function percentOf(int $cents, int $percent): int
{
return intdiv($cents * $percent + 50, 100);
}
function formatCents(int $cents): string
{
$sign = $cents < 0 ? "-" : "";
$cents = abs($cents);
return sprintf("%s%d.%02d", $sign, intdiv($cents, 100), $cents % 100);
}
$subtotal = 1999 * 3;
$discount = percentOf($subtotal, 15);
$total = $subtotal - $discount;
echo "Subtotal: " . formatCents($subtotal) . PHP_EOL;
echo "Discount: " . formatCents($discount) . PHP_EOL;
echo "Total: " . formatCents($total) . PHP_EOL;
echo "Refund: " . formatCents(-$discount) . PHP_EOL;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- PHP separates int from float; / returns an int only when exact, intdiv() gives the whole part and the sign of % follows the left operand.
- Int overflow turns into a float and 0.1 + 0.2 != 0.3, so compare floats with a tolerance, never ==.
- Keep money as whole integers of the smallest unit and prefer round() over an (int) cast.
- In PHP 8 numeric strings work in arithmetic, "12abc" warns and "abc" throws a TypeError, so validate input with filter_var().
PHP Language Reference — PHP Documentation Group