Edit in GitHubLog an issue
Thanks to Adarsh Manickam for contributing this topic!

Float comparator

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

MethodDescription
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

Copied to your clipboard
$isEqual = $this->floatComparator->equal(1.002, 1.002);

Checks if the first float is greater than the second float

Copied to your clipboard
$isGreater = $this->floatComparator->greaterThan(1.0004, 1.002);

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

Copied to your clipboard
$isGreaterOrEqual = $this->floatComparator->greaterThanOrEqual(1.0004, 1.0004);
  • Privacy
  • Terms of Use
  • Do not sell or share my personal information
  • AdChoices
Copyright © 2024 Adobe. All rights reserved.