I'm attempting to truncate a series of double-precision values in C#. The following value fails no matter what rounding method I use. What is wrong with this value that causes both of these methods to fail? Why does even Math.Round
fail to correctly truncate the number? What method can be used instead to correctly truncate such values?
The value :
double value = 0.61740451388888251;
Method 1:
return Math.Round(value, digits);
Method 2:
double multiplier = Math.Pow(10, decimals)
return Math.Round(value * multiplier) / multiplier;
Fails even in VS watch window!
Double is a floating binary point type. They are represented in binary system (like 11010.00110
). When double is presented in decimal system it is only an approximation as not all binary numbers have exact representation in decimal system. Try for example this operation:
double d = 3.65d + 0.05d;
It will not result in 3.7
but in 3.6999999999999997
. It is because the variable contains a closest available double
.
The same happens in your case. Your variable contains closest available double
.
For precise operations double
/float
is not the most fortunate choice. Use double
/float
when you need fast performance or you want to operate on larger range of numbers, but where high precision is not required. For instance, it is perfect type for calculations in physics. For precise decimal operations use, well, decimal
.
Here is an article about float
/decimal
: http://csharpindepth.com/Articles/General/FloatingPoint.aspx
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments