c# - .NET Web API 返回带有很多小数位的 double

标签 c# .net json double rounding

我正在使用 .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/

此处:Decimal rounding errors upon division (C#)

此处:http://csharpindepth.com/Articles/General/Decimal.aspx

关于c# - .NET Web API 返回带有很多小数位的 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22809051/

相关文章:

jquery - 使用 jquery 和 ajax 发送授权 header

c# - 查找数组中最低唯一值的索引

c# - 如何在不使用ajax的情况下将数据从View发送到Controller?

c# - Linq:确定序列中的项目数是否满足条件

c# - Regex.Replace 无法按预期使用 Regexoptions.IgnoreCase

c++ - 如何在COR Profiler中从AssemblyID获取Assembly Info?

.net - EWS : Appoitnment Item. Id.UniqueId 不是常量

C# 如何从我的用户控件访问主窗体上的 setter 方法?

json - 具有 50 个 CIDR IP 的安全组的 Cloudformation 模板(JSON)(入口)

json - 检查 JSON 中除条件中提到的对象之外的对象