HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Numbers

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.


1. Integers

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)
?>

2. Floats

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)
?>

3. Numerical Strings

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

Casting — Converting String to Number

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
?>
NaN (Not a Number): NaN is used for mathematical operations that are impossible, such as acos(8). You can use is_nan() to check for this value.

The number_format() Function

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
?>
Pro Tip: Always use is_numeric() before performing math on data from a user form ($_POST or $_GET). This prevents calculation errors and improves security.

Key Points to Remember

  • Use is_int() and is_float() to check specific types.
  • is_numeric() handles both numbers and numeric-strings (e.g., from forms).
  • Use (int) or (float) to manually convert data types.
  • number_format() is essential for user-friendly display of totals.
  • PHP handles math between different numeric types (int + float) automatically.