Best way of checking if a floating point is an integer

后端 未结 12 1967
陌清茗
陌清茗 2020-12-25 13:07

[There are a few questions on this but none of the answers are particularly definitive and several are out of date with the current C++ standard].

My research shows

12条回答
  •  时光取名叫无心
    2020-12-25 13:45

    Use modf() which breaks the value into integral and fractional parts. From this direct test, it is known if the double is a whole number or not. After this, limit tests against the min/max of the target integer type can be done.

    #include 
    
    bool IsInteger(double x) {
      double ipart;
      return std::modf(x, &ipart) == 0.0;  // Test if fraction is 0.0.
    }
    

    Note modf() differs from the similar named fmod().

    Of the 3 methods OP posted, the cast to/from an integer may perform a fair amount of work doing the casts and compare. The other 2 are marginally the same. They work, assuming no unexpected rounding mode effects from dividing by 1.0. But do an unnecessary divide.

    As to which is fastest likely depends on the mix of doubles used.

    OP's first method has a singular advantage: Since the goal is to test if a FP may convert exactly to a some integer, and likely then if the result is true, the conversion needs to then occur, OP's first method has already done the conversion.

提交回复
热议问题