How to check if float is a whole number?

后端 未结 1 1380
攒了一身酷
攒了一身酷 2021-01-18 17:51

There is some kind of function for the printf function in which you can use %g, which will show the whole number 3 if the float is 3.00 and will show 3.01

1条回答
  •  北海茫月
    2021-01-18 18:49

    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.

    0 讨论(0)
提交回复
热议问题