Floats Functions
Nette\Utils\Floats is a static class with useful functions for comparing float numbers.
Installation:
All examples assume the following class alias is defined:
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?
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:
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
.
isLessThan (float $a, float $b): bool
Returns true
if $a
< $b
.
isLessThanOrEqualTo (float $a, float $b): bool
Returns true
if $a
<= $b
.
isGreaterThan (float $a, float $b): bool
Returns true
if $a
> $b
.
isGreaterThanOrEqualTo (float $a, float $b): bool
Returns true
if $a
>= $b
.
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.
Helpers Functions
isZero (float $value): bool
Returns true
if value is zero.
isInteger (float $value): bool
Returns true
if value is integer.