Floats are numbers with decimals. They help us work with values that are not whole, like money or measurements.
0
0
Float type and precision in PHP
Introduction
When you need to store prices like 19.99 in a shopping cart.
When measuring distances or weights that are not whole numbers.
When calculating averages or percentages that result in decimal numbers.
When working with scientific data that requires decimal precision.
Syntax
PHP
$floatNumber = 3.14; $anotherFloat = 2.0; $scientificFloat = 1.5e3; // 1500 in scientific notation
Floats can be written with decimals or in scientific notation.
PHP stores floats with limited precision, so very long decimals may be rounded.
Examples
This creates a float for a price and prints it.
PHP
$price = 19.99; echo $price;
Stores a measurement with decimals and prints it.
PHP
$distance = 123.456; echo $distance;
Uses scientific notation for 12000 and prints it.
PHP
$bigNumber = 1.2e4; echo $bigNumber;
Sample Program
This program adds two floats and shows how float precision can cause unexpected results.
PHP
<?php $float1 = 0.1; $float2 = 0.2; $sum = $float1 + $float2; echo "Sum of 0.1 and 0.2 is: $sum\n"; // Show precision issue if ($sum == 0.3) { echo "Sum equals 0.3 exactly.\n"; } else { echo "Sum does NOT equal 0.3 exactly due to float precision.\n"; } ?>
OutputSuccess
Important Notes
Floats are not always exact because of how computers store decimal numbers.
For money, consider using integers (like cents) or special libraries to avoid precision errors.
Use functions like round() to control decimal places when displaying floats.
Summary
Floats store decimal numbers but have limited precision.
Be careful with equality checks on floats because of tiny rounding errors.
Use rounding or other methods to handle float precision in your programs.