PHP Tutorial · PHP Basics · Lesson 9 of 38

PHP Numbers and Math

Integers, floats, rounding, random numbers and number formatting.

Integers and floats

Example 1Try it yourself
<?php
var_dump(PHP_INT_MAX);
var_dump(7 / 2, intdiv(7, 2), 7 % 2, 2 ** 10);
var_dump(0.1 + 0.2 == 0.3);
var_dump(abs((0.1 + 0.2) - 0.3) < PHP_FLOAT_EPSILON);

Output

int(9223372036854775807)
float(3.5)
int(3)
int(1)
int(1024)
bool(false)
bool(true)

intdiv() does integer division; % gives the remainder; ** is power.

Math functions

Example 2Try it yourself
<?php
echo round(3.456, 2), " ", floor(3.9), " ", ceil(3.1), "\n";
echo max(4, 9, 2), " ", min([4, 9, 2]), "\n";
echo sqrt(81), " ", pi(), "\n";
echo abs(-15), "\n";

Output

3.46 3 4
9 2
9 3.1415926535898
15

Formatting numbers

number_format() adds thousands separators and fixes decimals — perfect for prices:

Example 3Try it yourself
<?php
echo number_format(1234567.891), "\n";
echo number_format(1234567.891, 2), "\n";
echo number_format(1234567.891, 2, ',', '.'), "\n";

Output

1,234,568
1,234,567.89
1.234.567,89

For exact money calculations, store cents as integers or use the bcmath extension.

Test yourself

Which function returns the integer result of 7 divided by 2?

  1. 7 / 2
  2. intdiv(7, 2)
  3. div(7, 2)
  4. 7 // 2
Show answer

Answer: intdiv(7, 2)