PHP provides built-in numeric types for whole numbers (int) and floating-point numbers (float or double), along with utility inspection functions and type casting tools.
int): 64-bit signed integers (on 64-bit systems) ranging from PHP_INT_MIN to PHP_INT_MAX.float): Double-precision floating-point numbers adhering to IEEE 754 standard.INF (Infinity) and NAN (Not a Number).flowchart LR
A["Raw Input Data"] --> B{"Numeric Inspection"}
B -- is_int($v) --> C["Process Whole Integer"]
B -- is_float($v) --> D["Process Floating-Point"]
B -- is_numeric($v) --> E["Cast or Parse Numeric String"]
B -- is_nan($v) / is_infinite($v) --> F["Handle Math Edge Case"]
<?php
declare(strict_types=1);
$quantity = 15; // int
$unitPrice = 49.99; // float
$rawInput = "150.75"; // numeric string
// 1. Numeric Checking Functions
echo "Is Quantity Int?: " . (is_int($quantity) ? "Yes" : "No") . "
";
echo "Is Price Float?: " . (is_float($unitPrice) ? "Yes" : "No") . "
";
echo "Is Raw Input Numeric?: " . (is_numeric($rawInput) ? "Yes" : "No") . "
";
// 2. Total Calculation & Formatting
$subtotal = $quantity * $unitPrice;
$formattedTotal = number_format($subtotal, 2, '.', ',');
echo "Calculated Subtotal: $" . $formattedTotal . "
";
// 3. Float Precision Edge Cases
$floatVal1 = 0.1 + 0.2;
$floatVal2 = 0.3;
// Never compare floats directly with == ! Use absolute threshold (epsilon)
$isEqual = abs($floatVal1 - $floatVal2) < 0.00001;
echo "Are Float Calculations Equal?: " . ($isEqual ? "Yes" : "No") . "
";
==: Always check abs($a - $b) < 0.00001 due to inherent binary floating-point representation rounding differences.is_numeric() to Validate Form Inputs: Validates both integers, floats, and numeric strings before casting.bcmath or Integer Cents for Monetary Calculations: Store financial amounts as integer cents ($19.99 -> 1999) or use bcadd() / bcmul() to prevent floating-point precision loss.Write a PHP script that checks if a string variable $input = "45.50" is numeric using is_numeric(), casts it to float, and formats it as currency using number_format()!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.