Curriculum
This lesson will teach you how to use floating-point numbers, sometimes known as floats, in PHP.
Floating-point numbers are numerical values that have decimal digits.
Floating-point numbers are also known as floats, doubles, and real numbers. The range of floats, like that of integers, is determined by the platform on which PHP is run.
PHP understands floating-point numbers in the following formats:
1.25 3.14 -0.1
PHP also supports scientific notation for floating-point numbers:
0.125E1 // 0.125 * 10^1 or 1.25
Since PHP 7.4, underscores in floats can be used to make long numbers more readable. As an example:
1_234_457.89
Because the computer cannot represent exact floating-point numbers, it can only use approximations.
For example, 0.1 + 0.1 + 0.1 equals 0.299999999…, not 0.3. It means you must exercise caution when comparing two floating-point numbers with the == operator.
The following example yields false, which may or may not be what you expected:
<?php $total = 0.1 + 0.1 + 0.1; echo $total == 0.3; // return false
The is float() or is_real() functions are used to determine whether a value is a floating-point number. If the argument is a floating-point number, is float() returns true; otherwise, it returns false. As an example:
echo is_float(0.5);
Output
1