Test if a floating point number is an integer

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

    I cannot answer the C#-specific part of the question, but I must point out you are probably missing a generic problem with floating point numbers.

    Generally, integerness is not well defined on floats. For the same reason that equality is not well defined on floats. Floating point calculations normally include both rounding and representation errors.

    For example, 1.1 + 0.6 != 1.7.

    Yup, that's just the way floating point numbers work.

    Here, 1.1 + 0.6 - 1.7 == 2.2204460492503131e-16.

    Strictly speaking, the closest thing to equality comparison you can do with floats is comparing them up to a chosen precision.

    If this is not sufficient, you must work with a decimal number representation, with a floating point number representation with built-in error range, or with symbolic computations.

提交回复
热议问题