<分区>
float ff = (float)31.15;
double dd = 31.15;
var frst = Math.Round(ff, 1, MidpointRounding.AwayFromZero);
var drst = Math.Round(dd, 1, MidpointRounding.AwayFromZero);
第一:31.1
drst:31.2
谁能解释一下为什么?
<分区>
float ff = (float)31.15;
double dd = 31.15;
var frst = Math.Round(ff, 1, MidpointRounding.AwayFromZero);
var drst = Math.Round(dd, 1, MidpointRounding.AwayFromZero);
第一:31.1
drst:31.2
谁能解释一下为什么?
最佳答案
嗯,Math.Round
想要double
,而不是float
,这就是原因
Math.Round(ff, 1, MidpointRounding.AwayFromZero);
等于
Math.Round((double)ff, 1, MidpointRounding.AwayFromZero);
如果我们检查 (double)ff
值
Console.Write(((double)ff).ToString("R"));
我们将在行动中看到舍入错误
31.149999618530273
最后,Math.Round(31.149999618530273, 1, MidpointRounding.AwayFromZero) == 31.1
符合预期
关于c# - C# 中的 float / double Math.Round,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54235885/