Reputation: 6088
What would be the most efficient way to say that float value is half of integer for example 0.5, 1.5, 10.5?
First what coming on my mind is:
$is_half = (($number - floor($number)) === 0.5);
Is there any better solutions?
Upvotes: 0
Views: 1702
Reputation: 165261
Due to floating point precision errors, you usually should check to see that the difference is below some low amount (but note that 0.5
is representable exactly, so it shouldn't be a problem, but it is in general with floats).
So your code is good for your specific sense, in general, you might want to do:
if (abs($number - floor($number) - $decimal) < 0.0001) {
Where $decimal
is your looking difference: 0.5
.
Upvotes: 4
Reputation: 6038
if(abs($number) - (int)(abs($number)) == 0.5) {
// half of an integer.
}
Upvotes: 0