Skip to content
PHP Logo

What best practices should be followed when comparing float values in PHP?

When comparing float values in PHP, it is important to be aware of floating-point precision issues that can lead to unexpected results. To compare float values accurately, it is recommended to use the PHP function `abs()` with a very small epsilon value to determine if two float values are close enough to be considered equal.

php
$epsilon = 0.00001;
$float1 = 0.1 + 0.2;
$float2 = 0.3;

if (abs($float1 - $float2) < $epsilon) {
    echo "Float values are considered equal.";
} else {
    echo "Float values are not equal.";
}