PHP 7.3 reaches end of support in December 2021 and Adobe Commerce 2.3.x reaches end of support in April 2022. You may want to consider planning your upgrade now to Adobe Commerce 2.4.x and PHP 7.4.x to help maintain PCI compliance.

Float Comparator

Overview

The Magento\Framework\Math\FloatComparator library provides methods to compare float values with an approriate epsilon value (0.00001). Floats usually have rounding errors while doing mathematical operations, so the conventional way of comparing two floats using the equality operator (==), may not always lead to expected results. For more information, please refer to this article.

Usage

Method Description
equal Compares two given floats and returns a boolean value describing if they’re equal.
greaterThan Compares two given floats and returns a boolean value describing if the first float is greater than the second float.
greaterThanOrEqual Compares two given floats and returns a boolean value describing if the first float is greater than or equal to the second float.

Examples

In the examples below, the $this->floatComparator property is an instantiated object of the Magento\Framework\Math\FloatComparator class.

Check if two floats are equal

1
$isEqual = $this->floatComparator->equal(1.002, 1.002);

Checks if the first float is greater than the second float

1
$isGreater = $this->floatComparator->greaterThan(1.0004, 1.002);

Checks if the first float is greater than or equal to the second float

1
$isGreaterOrEqual = $this->floatComparator->greaterThanOrEqual(1.0004, 1.0004);