什么是检查是否一个浮点变量是一个整数的最可靠的方法是什么? [英] What is the most reliable way of checking if a floating point variable is an integer?
问题描述
我能想到的几种方法,如:
I can think of several ways, eg.
Convert.ToInt32(floatingPoint) - floatingPoint == 0;
Math.Truncate(floatingPoint) - floatingPoint == 0;
floatingPoint % 1 == 0;
Math.Floor(floatingPoint) == floatingPoint;
//etc...
但是哪种方法最可靠?
But which method is most reliable?
推荐答案
您不应该检查精确的平等到零,作为一个浮点数通常只包含最接近的可能近似您分配给数吧。
You should not check for exact equality to zero, as a floating point number usually only contains the closest possible approximation to the number that you assigned to it.
例如,最接近的可能值42的类型可以代表可能是这样的42.00000000000000662,你还是会希望算作一个整数值。
For example, the closest possible value to 42 that the type could represent might be something like 42.00000000000000662, which you still would want to count as an integer value.
取值和舍入值之间的差额,再取的绝对值(因此,它不是负),并比较小的值:
Take the difference between the value and the rounded value, then take the absolute value of that (so that it's not negative) and compare to a small value:
if (Math.Abs(Math.Round(floatingPoint) - floatingPoint) < 0.000001) ...
这篇关于什么是检查是否一个浮点变量是一个整数的最可靠的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!