Test if a floating point number is an integer

前端 未结 12 2375
醉酒成梦
醉酒成梦 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条回答
  •  甜味超标
    2021-02-18 22:51

    This will let you choose what precision you're looking for, plus or minus half a tick, to account for floating point drift. The comparison is integral also which is nice.

    static void Main(string[] args)
    {
        const int precision = 10000;
    
        foreach (var d in new[] { 2, 2.9, 2.001, 1.999, 1.99999999, 2.00000001 })
        {
            if ((int) (d*precision + .5)%precision == 0)
            {
                Console.WriteLine("{0} is an int", d);
            }
        }
    }
    

    and the output is

    2 is an int
    1.99999999 is an int
    2.00000001 is an int
    

提交回复
热议问题