正如问题所暗示的那样(更多的是声明抱歉)我在 C# 中使用 math.truncate 时遇到问题。我想做的是,当一个数字的小数除以 50 等于 0.4 时,这样做,如下所示:
double temp2 = 170;
temp2 = temp2 / 50; //this equals 3.4
temp2 -= Math.Truncate(temp2);
if (temp2 == 0.4)
{
Console.WriteLine("Hello");
}
但是,当我尝试执行此操作时,它对我不起作用,而且我不确定为什么它不起作用,请问我能否让某人对此有所了解并让我朝着正确的方向前进?
最佳答案
single
和 double
是二进制浮点类型。这意味着它们不能准确地表示许多小数值(如 0.4)。这可能会导致细微的舍入错误,因此比较逻辑上应该表示相同值的两个 double
值可能会导致意外结果。
这可以使用 DoubleToInt64Bits
根据经验进行验证方法:
BitConverter.DoubleToInt64Bits(temp2); // 4600877379321698712
BitConverter.DoubleToInt64Bits(0.4); // 4600877379321698714
将其更改为decimal
,您将获得预期的结果:
decimal temp2 = 170;
temp2 = temp2 / 50; //this equals 3.4
temp2 -= Math.Truncate(temp2);
if (temp2 == 0.4m) // the m creates a decimal constant
{
Console.WriteLine("Hello");
}
关于c# - Math.Truncate(number) 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18649020/