How to test for lossless double / integer conversion?

前端 未结 3 1388
夕颜
夕颜 2021-02-18 13:20

I have one double, and one int64_t. I want to know if they hold exactly the same value, and if converting one type into the other does not lose any information.

My curre

3条回答
  •  滥情空心
    2021-02-18 13:40

    In addition to Pascal Cuoq's elaborate answer, and given the extra context you give in comments, I would add a test for negative zeros. You should preserve negative zeros unless you have good reasons not to. You need a specific test to avoid converting them to (int64_t)0. With your current proposal, negative zeros will pass your test, get stored as int64_t and read back as positive zeros.

    I am not sure what is the most efficient way to test them, maybe this:

    int int64EqualsDouble(int64_t i, double d) {
        return (d >= INT64_MIN)
            && (d < INT64_MAX)
            && (round(d) == d)
            && (i == (int64_t)d
            && (!signbit(d) || d != 0.0);
    }   
    

提交回复
热议问题