PHP provides rich support for numerical data. Whether you're building a simple calculator, an e-commerce cart, or a complex financial dashboard, understanding how PHP handles Integers and Floats is vital.
An integer is a whole number (without decimals) and it must have at least one digit. In PHP, integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation.
<?php
$x = 5985;
var_dump(is_int($x)); // Outputs: bool(true)
$y = 59.85;
var_dump(is_int($y)); // Outputs: bool(false)
?>
A float is a number with a decimal point or a number in exponential form. They are also known as "doubles" or "real numbers."
<?php
$x = 10.365;
var_dump(is_float($x)); // Outputs: bool(true)
?>
The is_numeric() function is extremely helpful when handling user input. It
checks if a variable is a number or a numeric string (like "50" or "4.5").
<?php
$x = 5985;
var_dump(is_numeric($x)); // true
$y = "5985";
var_dump(is_numeric($y)); // true (string is numeric)
$z = "Hello";
var_dump(is_numeric($z)); // false
?>
Sometimes you need to treat a string as a number manually. This process is called Type Casting. You can do this by placing the type in parentheses before the variable.
<?php
// Cast float to int
$x = 23465.768;
$int_cast = (int)$x;
echo $int_cast; // Outputs: 23465
// Cast string to int
$y = "23465.768";
$int_cast = (int)$y;
echo $int_cast; // Outputs: 23465
?>
acos(8). You can use is_nan() to check for
this value.
When displaying currency or large numbers, you want control over decimals and thousands separators.
<?php
$num = 12345.678;
echo number_format($num, 2); // Outputs: 12,345.68
?>
is_numeric() before performing math on
data from a user form ($_POST or $_GET). This prevents
calculation errors and improves security.