如何定义float是数字的一半? [英] How to define that float is half of the number?

查看:183
本文介绍了如何定义float是数字的一半?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浮点值是整数的一半,例如0.5,1.5,10.5,最有效的方法是什么?

首先我想到的是:

  $ is_half =(($ number  -  floor($ number))=== 0.5); 

是否有更好的解决方案?

解决方案

由于浮点精度的错误,你通常应该检查,看看差异是低于一些低数额(但请注意0.5可以准确表示,所以它不应该是一个问题。它通常与浮游物)。所以你的代码对于你的具体意义是有好处的,一般来说你可能会这样做:

  if(abs($ number  -  floor ($ number) -  $ decimal)<0.0001){


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?

解决方案

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) {

这篇关于如何定义float是数字的一半?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆