Floats Functions
Nette\Utils\Floats is a static class with useful functions for comparing float numbers.
Installation:
composer require nette/utils
All examples assume the following class alias is defined:
use Nette\Utils\Floats;
Motivation
Wondering what a float comparison class is for? You can use operators <
, >
, ===
,
you think. This is not entirely true. What do you think will print this code?
$a = 0.1 + 0.2;
$b = 0.3;
echo $a === $b ? 'same' : 'not same';
If you run the code, some of you will be surprised that the program printed not same
.
Mathematical operations with float numbers cause errors due to conversion between decimal and binary systems. For example
0.1 + 0.2
equates to 0.300000000000000044…
. Therefore, when comparing floats, we must tolerate a small
difference from a certain decimal place.
And that's what the Floats
class is doing. The following comparison will work as expected:
echo Floats::areEqual($a, $b) ? 'same' : 'not same'; // same
When trying to compare NAN
, it throws an \LogicException
exception.
The Floats
class tolerates differences less than 1e-10
. If you need to work with more
precision, use the BCMath library instead.
Float Comparison
areEqual(float $a, float $b): bool
Returns true
if $a
= $b
.
Floats::areEqual(10, 10.0); // true
isLessThan(float $a, float $b): bool
Returns true
if $a
< $b
.
Floats::isLessThan(9.5, 10.2); // true
Floats::isLessThan(INF, 10.2); // false
isLessThanOrEqualTo(float $a, float $b): bool
Returns true
if $a
<= $b
.
Floats::isLessThanOrEqualTo(9.5, 10.2); // true
Floats::isLessThanOrEqualTo(10.25, 10.25); // true
isGreaterThan(float $a, float $b): bool
Returns true
if $a
> $b
.
Floats::isGreaterThan(9.5, -10.2); // true
Floats::isGreaterThan(9.5, 10.2); // false
isGreaterThanOrEqualTo(float $a, float $b): bool
Returns true
if $a
>= $b
.
Floats::isGreaterThanOrEqualTo(9.5, 10.2); // false
Floats::isGreaterThanOrEqualTo(10.2, 10.2); // true
compare(float $a, float $b): int
If $a
< $b
, it returns -1
, if they are equal it returns 0
and if
$a
> $b
it returns 1
.
It can be used, for example, with the usort
function.
$arr = [1, 5, 2, -3.5];
usort($arr, [Float::class, 'compare']);
// $arr is [-3.5, 1, 2, 5]
Helpers Functions
isZero(float $value): bool
Returns true
if value is zero.
Floats::isZero(0.0); // true
Floats::isZero(0); // true
isInteger(float $value): bool
Returns true
if value is integer.
Floats::isInteger(0); // true
Floats::isInteger(0.0); // true
Floats::isInteger(-5.0); // true
Floats::isInteger(-5.1); // false
Floats::isInteger(INF); // false
Floats::isInteger(NAN); // false