I am having the function to truncate the decimal places of the double datatype vaiable which is given below
public double GetTruncate(double tobeTruncated, int divideFactor)
{
if (divideFactor == 0)
return Math.Truncate((double)tobeTruncated);
else
{
tobeTruncated = tobeTruncated * divideFactor;
tobeTruncated = Math.Truncate((double)tobeTruncated);
tobeTruncated = tobeTruncated / divideFactor;
}
return tobeTruncated;
}
Example : tobeTruncated = 35.66 dividefactor = 100
While executing the above line , i am getting the value for tobeTruncated as 3565.9999999999995,instead of 3566. I dont know the reason.
When i changed the double variable to decimal , i am getting the correct answer. The modified function with correct answer is given below :
public double GetTruncate(double tobeTruncated, int divideFactor)
{
decimal nTempData = (decimal)tobeTruncated;
if (divideFactor == 0)
return (double)Math.Truncate((decimal)nTempData);
else
{
nTempData = nTempData * divideFactor;
nTempData = Math.Truncate((decimal)nTempData);
nTempData = nTempData / (decimal)divideFactor;
}
return (double)nTempData;
}
Can anyone explain the reason behind this?