PHP handles integers (int) and decimals (float, also called double) as separate types, and provides a set of built-in functions for the operations that come up constantly.
| Function | What it does | Example |
|---|---|---|
| round($n) | Rounds to the nearest whole number | round(4.5) → 5 |
| round($n, $decimals) | Rounds to a set number of decimal places | round(3.14159, 2) → 3.14 |
| floor($n) | Always rounds down | floor(4.9) → 4 |
| ceil($n) | Always rounds up | ceil(4.1) → 5 |
<?php
echo abs(-7); // 7 — absolute value
echo max(3, 9, 2); // 9 — largest of the arguments
echo min(3, 9, 2); // 2 — smallest of the arguments
echo pow(2, 10); // 1024 — same as 2 ** 10
echo sqrt(64); // 8
echo rand(1, 100); // a random integer between 1 and 100
?>number_format() is worth knowing specifically — it's the standard way to turn a raw number into something readable, with thousands separators and a fixed number of decimals:
<?php
echo number_format(1234567.891, 2); // "1,234,567.89"
?>Division and floats
Division always returns a float in PHP unless both operands are integers and divide evenly (10 / 2 gives the int 5, but 10 / 3 gives a float). Use the modulus operator % from the Operators lesson if you specifically need the integer remainder.