Test if a floating point number is an integer

前端 未结 12 2401
醉酒成梦
醉酒成梦 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:49

    To handle the precision of the double...

    Math.Abs(d - Math.Floor(d)) <= double.Epsilon
    

    Consider the following case where a value less then double.Epsilon fails to compare as zero.

    // number of possible rounds
    const int rounds = 1;
    
    // precision causes rounding up to double.Epsilon
    double d = double.Epsilon*.75;
    
    // due to the rounding this comparison fails
    Console.WriteLine(d == Math.Floor(d));
    
    // this comparison succeeds by accounting for the rounding
    Console.WriteLine(Math.Abs(d - Math.Floor(d)) <= rounds*double.Epsilon);
    
    // The difference is double.Epsilon, 4.940656458412465E-324
    Console.WriteLine(Math.Abs(d - Math.Floor(d)).ToString("E15"));
    

提交回复
热议问题