Best way of checking if a floating point is an integer

后端 未结 12 1978
陌清茗
陌清茗 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 14:03

    If your question is "Can I convert this double to int without loss of information?" then I would do something simple like :

    template 
    bool CanConvert(U u)
    {
      return U(T(u)) == u;
    }
    
    CanConvert(1.0) -- true
    CanConvert(1.5) -- false
    CanConvert(1e9) -- true
    CanConvert(1e10)-- false
    

提交回复
热议问题