in CSharp,
why??Code:double d = 0.10 + 0.10 + 0.10;
//d=0.30000000000000004;
Printable View
in CSharp,
why??Code:double d = 0.10 + 0.10 + 0.10;
//d=0.30000000000000004;
A double is a 64bit value encoded in base 2 format, or binary. Some numbers, like .10 do not have a binary representation so a rough approximation must be used and will not be 100% accurate. I believe it has a error of around 3% though I could be wrong.
If you want precision use decimal. Decimal is a 128bit value encoded in base 10 format, or decimal. This can store any decimal number and you will not loose precision with a value such as .10.
Precision aside, calculations using doubles are quicker because they are base 2 and the computer understands this better than base 10. Doubles also have a much wider range of possible values and take up less storage space. Most math done in applications will work fine with doubles, but once you start dealing with financial applications or anything that really needs the precision you need to use decimals.
Just to expand on the above post - this isn't a C# issue, it's just something you have to live with when using floating point math. It's just how floats and doubles work. This is why you should never compare doubles using "==", you should always do something like:
Of course, the value of 'epsilon' that you choose is up to you. If this isn't good enough, then you shouldn't use floats/doubles.Code:double epsilon = 0.0001;
double val1 = 0.1 + 0.1 + 0.1;
if (Math.Abs (val1 - 0.3) < epsilon)
Console.WriteLine ("values are the same");
else
Console.WriteLine ("Values are not the same");