← Back to PHP Course | Chapter 1: Introduction & Basics | Lesson 13 of 13

PHP Numbers

Integer and Float Types

PHP has two core numeric types: int for whole numbers and float (also called double) for numbers with a decimal point or in exponential notation. PHP is dynamically typed, so a variable can hold an int in one line and a float the next -- the type is inferred from the literal you assign, not declared up front.

Example: Integer and Float Types

php
<?php
$a = 10;
$b = 10.5;
var_dump($a);
var_dump($b);
?>

Integer Limits and Overflow

Every platform has a maximum integer size, exposed in PHP as the PHP_INT_MAX constant (typically 9223372036854775807 on 64-bit systems). Adding 1 past that limit doesn't wrap around or error -- PHP silently promotes the result to a float, which can lose precision for very large numbers, so relying on exact integer arithmetic near that boundary is risky.

Example: Integer Limits and Overflow

php
<?php
echo PHP_INT_MAX . "\n";
var_dump(PHP_INT_MAX + 1);
?>

Floating-Point Precision

Floats are stored in binary, and many decimal fractions -- like 0.1 -- can't be represented exactly in binary, the same issue every language built on IEEE 754 floats has. This is why 0.1 + 0.2 == 0.3 can evaluate to false in PHP; comparing floats for exact equality is a common source of subtle bugs, and rounding to a fixed precision before comparing is the usual fix.

Example: Floating-Point Precision

php
<?php
var_dump(0.1 + 0.2 == 0.3);
echo round(0.1 + 0.2, 10) == round(0.3, 10) ? "Equal after rounding" : "Still unequal";
?>

Numeric Strings

PHP treats strings like "42" or "3.14" as numeric strings and will automatically convert them for arithmetic -- "5" + "3" evaluates to 8, not a string concatenation. PHP 8 tightened the rules for what counts as a valid numeric string, and non-numeric strings used in arithmetic now throw a TypeError instead of silently becoming 0 as in older versions.

Example: Numeric Strings

php
<?php
echo "5" + "3";
?>

Number Formatting and Conversion

Functions like number_format(), round(), intval(), and floatval() convert between formats and precision levels for display or storage. number_format() is especially useful for adding thousands separators and a fixed decimal count when showing prices or large counts to users, something raw echo of a float won't do correctly.

Example: Number Formatting and Conversion

php
<?php
echo number_format(1234567.891, 2) . "\n";
echo round(4.567, 1) . "\n";
echo intval("42abc");
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.