How to check if float is a whole number?

旧城冷巷雨未停 提交于 2019-12-01 17:45:37

There isn't really a simple answer

Integral values do have exact representations in the float and double formats. So, if it's really already integral, you can use:

f == floor(f)

However, if your value is the result of a calculation which at one point involved any sort of non-zero fractional part, then you will need to be concerned that you may have something very close to an integer but which isn't really, exactly, to-the-last-bit the same. You probably want to consider that to be integral.

One way this might be done:

fabs(f - round(f)) < 0.000001

And while we are on the subject, for the purists, we should note that int i = f; or double i = f; will round according to the FPU mode whereas round(3) will round half-way cases away from zero.

Try double modf( double, double * ) function. [http://www.codecogs.com/reference/computing/c/math.h/modf.php][1]

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