Search code examples
c#mathfloating-pointfloating-accuracycalculation

Incorrect calculation in C#


Why (0.406 * 10000.0) returns 4060.0000000000005 instead of 4060.0 in C#

I have written a function which checks no. of decimals in a double value and below is the code I am using. The problem described in the above sentence occurs when value of d is 0.406 and values of n is 4 and the function returns true instead of false

I am open to using alternate solution.

public static bool HasMoreThanNDecimals(double d, int n)
{
    return !(d * (double)Math.Pow(10, n) % 1 == 0);
}

Solution

  • Just use decimal type instead of double for more precision to get the desired result.

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/921a8ffc-9829-4145-bdc9-a96c1ec174a5/decimal-vs-double-difference?forum=csharpgeneral