Test if a floating point number is an integer

前端 未结 12 2433
醉酒成梦
醉酒成梦 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条回答
  •  旧时难觅i
    2021-02-18 22:37

    If you are just going to convert it, Mike F / Khoth's answer is good, but doesn't quite answer your question. If you are going to actually test, and it's actually important, I recommend you implement something that includes a margin of error.

    For instance, if you are considering money and you want to test for even dollar amounts, you might say (following Khoth's pattern):

    if( Math.abs(d - Math.Floor(d + 0.001)) < 0.001)
    

    In other words, take the absolute value of the difference of the value and it's integer representation and ensure that it's small.

提交回复
热议问题