Test if a floating point number is an integer

前端 未结 12 2432
醉酒成梦
醉酒成梦 2021-02-18 22:21

This code works (C# 3)

double d;
if(d == (double)(int)d) ...;
  1. Is there a better way to do this?
  2. For extraneous reasons I want to
12条回答
  •  Happy的楠姐
    2021-02-18 22:50

    A simple test such as 'x == floor(x)' is mathematically assured to work correctly, for any fixed-precision FP number.

    All legal fixed-precision FP encodings represent distinct real numbers, and so for every integer x, there is at most one fixed-precision FP encoding that matches it exactly.

    Therefore, for every integer x that CAN be represented in such way, we have x == floor(x) necessarily, since floor(x) by definition returns the largest FP number y such that y <= x and y represents an integer; so floor(x) must return x.

提交回复
热议问题