c# - 检查浮点变量是否为整数的最可靠方法是什么?

标签 c# floating-point isinteger

我可以想到几种方法,例如。

Convert.ToInt32(floatingPoint) - floatingPoint == 0;
Math.Truncate(floatingPoint) - floatingPoint == 0;
floatingPoint % 1 == 0;
Math.Floor(floatingPoint) == floatingPoint;
//etc...

但是哪种方法最可靠呢?

最佳答案

您不应该检查是否完全等于零,因为 float 通常只包含与您分配给它的数字最接近的近似值。

例如,该类型可以表示的最接近 42 的可能值可能类似于 42.00000000000000662,您仍然希望将其计为整数值。

取该值与四舍五入后的值之差,然后取其绝对值(使其不是负值)并与较小的值进行比较:

if (Math.Abs(Math.Round(floatingPoint) - floatingPoint) < 0.000001) ...

关于c# - 检查浮点变量是否为整数的最可靠方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/638376/

相关文章:

swift - 在 Swift 4 中,将 String 值类型转换为 Float 值的正确方法是什么?

java - 舍入误差近似值

java - 基本Java : Method to tell if a double is an integer

.net - 如何检查数字是否为 .NET 中的整数?

c# - 直到应用程序关闭才发送电子邮件

three.js - 为什么 Three.js 几何体在处理大量数字时会失去精度?

c# - MvvmCross : conventional plugin bypass

判断一个值是否为整数的Javascript函数

c# - ',' 附近的语法不正确。 SQL Server 和 C#

c# - "Reflection": Method with "params" does not initialize my custom Objects