PHP Numbers — Complete Guide to Integers, Floats, and Mathematical Operations
In this tutorial, you will learn about PHP Numbers. We cover key concepts, practical examples, and best practices to help you master this topic.
PHP numbers include integers (whole numbers) and floats (decimal numbers), with built-in functions for arithmetic, rounding, random generation, and mathematical operations.
What You'll Learn
By the end of this tutorial, you'll work with PHP integers and floats, handle precision issues, use math functions, generate random numbers, format currency, and validate numeric input.
Why PHP Numbers Matter
E-commerce, financial calculations, data analysis, and scientific computing all depend on correct number handling. Understanding PHP's numeric quirks prevents calculation errors.
Real-World Use
An e-commerce platform calculates prices, taxes, discounts, and totals. Using proper rounding and precision ensures customers are charged correct amounts and financial reports are accurate.
PHP Numbers Learning Path
flowchart LR
A[Strings] --> B[Numbers]
B --> C[Operators]
C --> D[Control Flow]
D --> E[Loops]
A --> F{You Are Here}
style F fill:#f90,color:#fff
Integer Operations
<?php
$a = 42; // decimal
$b = 0x2A; // hexadecimal (42)
$c = 0b101010; // binary (42)
echo PHP_INT_MAX; // 9223372036854775807 (64-bit)
echo PHP_INT_MIN; // -9223372036854775808
echo PHP_INT_SIZE; // 8 (bytes)
Float Precision
<?php
echo 0.1 + 0.2; // 0.30000000000000004
echo round(0.1 + 0.2, 1); // 0.3
echo floor(3.7); // 3
echo ceil(3.2); // 4
// Use BCMath for precision
echo bcadd("0.1", "0.2", 2); // 0.30
Math Functions
<?php
echo abs(-5); // 5
echo max(3, 7, 2); // 7
echo min(3, 7, 2); // 2
echo sqrt(16); // 4
echo pow(2, 10); // 1024
echo pi(); // 3.1415926535898
Random Numbers
<?php
echo rand(1, 10); // Random integer 1-10
echo mt_rand(1, 10); // Faster random (use this)
echo random_int(1, 10); // Cryptographically secure
Number Formatting
<?php
echo number_format(1234567.89, 2); // 1,234,567.89
echo number_format(1234567.89, 2, ",", "."); // 1.234.567,89 (European)
Number Validation
<?php
var_dump(is_numeric("42")); // true
var_dump(is_numeric("42.5")); // true
var_dump(is_numeric("abc")); // false
var_dump(is_int(42)); // true
var_dump(is_float(3.14)); // true
var_dump(filter_var("42", FILTER_VALIDATE_INT)); // 42
var_dump(filter_var("abc", FILTER_VALIDATE_INT)); // false
Common Mistakes
1. Comparing Floats Directly
0.1 + 0.2 !== 0.3 due to floating-point precision. Use round() or compare with epsilon tolerance.
2. Not Using BCMath for Financial Calculations
Float imprecision causes cent errors in financial calculations. Use bcadd, bcsub, bcmul, bcdiv for money.
3. Assuming is_numeric Guarantees Valid Number
is_numeric returns true for hex strings like "0xFF". Use filter_var with FILTER_VALIDATE_INT or FILTER_VALIDATE_FLOAT.
4. Integer Overflow
PHP automatically converts to float when integers exceed PHP_INT_MAX. Check with is_int() if exact integer is required.
5. Using rand() for Security
rand() and mt_rand() are not cryptographically secure. Use random_int() for tokens, passwords, and secrets.
Practice Questions
1. What is PHP_INT_MAX?
The maximum integer value on the system: 9223372036854775807 on 64-bit. Larger values become floats.
2. Why does 0.1 + 0.2 not equal 0.3?
Floating-point binary representation can't precisely represent 0.1 and 0.2. Always use round() for comparison.
3. What is the difference between rand, mt_rand, and random_int?
rand is basic. mt_rand is faster (Mersenne Twister). random_int is cryptographically secure.
4. How do you format a number as currency?
Use number_format($amount, 2) or sprintf("$%.2f", $amount) for basic formatting.
5. Challenge: Create a function that safely calculates a percentage with correct rounding.
<?php
function calculatePercentage(float $partial, float $total, int $precision = 2): float {
if ($total == 0) return 0.0;
return round(($partial / $total) * 100, $precision);
}
echo calculatePercentage(25, 200); // 12.5
echo calculatePercentage(1, 3, 4); // 33.3333
FAQ
Mini Project: Shopping Cart Calculator
Build a shopping cart total calculator with proper tax and discount handling.
<?php
function calculateTotal(array $items, float $taxRate = 0.08, float $discount = 0): array {
$subtotal = array_sum(array_column($items, "price"));
$discountAmount = round($subtotal * $discount, 2);
$afterDiscount = round($subtotal - $discountAmount, 2);
$tax = round($afterDiscount * $taxRate, 2);
$total = round($afterDiscount + $tax, 2);
return ["subtotal" => $subtotal, "discount" => $discountAmount,
"tax" => $tax, "total" => $total];
}
$items = [["name" => "Book", "price" => 15.99], ["name" => "Pen", "price" => 2.50]];
print_r(calculateTotal($items, 0.1, 0.15));
What's Next
PHP Operators PHP Boolean Logic PHP Arrays
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro