我正在使用 .Net Web API 返回具有 double 的信息。在我回来之前,我将这些 double 四舍五入到小数点后两位。当我打印它们时,我得到(f.e):145,92。一切都很棒。但是当我返回那个 double 时,我的 JSON 响应是用这样的 double 创建的:
"hours":145.92000000000002
知道是什么造成了这个问题吗?
我的舍入函数是:
public double ApplyRounding(double value, int digits)
{
decimal decValue = (decimal)value;
// First round is to fix rounding errors by changing things like 0.99499999999999 to 0.995
decValue = Math.Round(decValue, digits + 5, MidpointRounding.AwayFromZero);
decValue = Math.Round(decValue, digits, MidpointRounding.AwayFromZero);
return (double)decValue;
}
谢谢
最佳答案
是的,这就是所谓的“双舍入”问题。您可以通过将 double 转换为 decimal、对其执行数学运算,然后再转换回 double 来获得它。
一些相关链接:
此处:http://www.exploringbinary.com/double-rounding-errors-in-floating-point-conversions/
关于c# - .NET Web API 返回带有很多小数位的 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22809051/