Test if a floating point number is an integer

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

    d == Math.Floor(d)
    

    does the same thing in other words.

    NB: Hopefully you're aware that you have to be very careful when doing this kind of thing; floats/doubles will very easily accumulate miniscule errors that make exact comparisons (like this one) fail for no obvious reason.

提交回复
热议问题