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);
}
Just use decimal type instead of double for more precision to get the desired result.