PHP supports two types of numbers: integers and floating-point numbers. Let’s take a look at both:
An integer
is a whole number (positive or negative) without decimals. Here’s an example:
<?php
$number = 42;
echo "The value of the integer is: " . $number . "<br>";
?>
The value of the integer is: 42
A float
is a number with a decimal point. It can also represent numbers in exponential notation. Here’s an example:
<?php
$price = 15.75;
echo "The value of the float is: " . $price . "<br>";
?>
The value of the float is: 15.75
PHP also supports numbers in exponential notation. This is useful when working with very large or very small numbers. Here’s an example:
<?php
$exp_num = 1.23e3; // 1.23 * 10^3
echo "The value of the exponential number is: " . $exp_num . "<br>";
?>
The value of the exponential number is: 1230
You can cast a variable to a different data type. In this case, converting a float to an integer. Here’s an example:
<?php
$float_num = 12.78;
$int_num = (int)$float_num;
echo "The integer value after casting is: " . $int_num . "<br>";
?>
The integer value after casting is: 12
Understanding how PHP handles numbers is essential for performing calculations, handling pricing, and working with data that requires numeric precision.