.NET Web API 返回带有大量小数位的双精度
本文关键字:小数 双精度 Web API 返回 NET | 更新日期: 2023-09-27 17:56:13
我正在使用.Net Web API返回具有双精度的信息。在我返回之前,我将这些双精度四舍五入到小数点后两位。当我打印它们时,我得到(f.e):145,92。都很棒。但是当我返回该双精度值时,我的 JSON 响应是使用如下所示的双精度创建的:
"小时":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;
}
谢谢
是的,它被称为"双重舍入"问题。您可以通过将双精度转换为十进制,对其执行数学运算,然后转换回双精度来获得它。
一些相关链接:
这里: http://www.exploringbinary.com/double-rounding-errors-in-floating-point-conversions/
此处:除法时的小数舍入误差 (C#)
在这里: http://csharpindepth.com/Articles/General/Decimal.aspx