Getting Started with PHP Numbers


Understanding PHP Numbers

PHP supports two types of numbers: integers and floating-point numbers. Let’s take a look at both:

1. Integer

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>";
?>

Output:

The value of the integer is: 42

2. Float

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>";
?>

Output:

The value of the float is: 15.75

3. Exponential (Scientific) Notation

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>";
?>

Output:

The value of the exponential number is: 1230

4. Type Casting

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>";
?>

Output:

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.