Pregunta

I am using .Net Web API to return information that has doubles. Before I return I round those doubles to two decimal places. When I print them I get(f.e): 145,92. All great. But when I return that double, my JSON response is created with a double like this:

"hours":145.92000000000002

Any ideas what is creating this issue?

My rounding function is:

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;
    }

Thanks

¿Fue útil?

Solución

Yep, it's known as "double rounding" problems. You get it from converting your double to decimal, performing math on it, then converting back to double.

A few related links:

Here: http://www.exploringbinary.com/double-rounding-errors-in-floating-point-conversions/

Here: Decimal rounding errors upon division (C#)

Here: http://csharpindepth.com/Articles/General/Decimal.aspx

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top