How to define that float is half of the number?

南楼画角 提交于 2020-01-06 18:53:32

问题


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?


回答1:


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.




回答2:


if(abs($number) - (int)(abs($number)) == 0.5) {
    // half of an integer.
}


来源:https://stackoverflow.com/questions/4769388/how-to-define-that-float-is-half-of-the-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!