Possible Duplicate:
Why is floating point arithmetic in C# imprecise?
I have been dealing with some numbers and C#, and the following line of code results in a different number than one would expect:
double num = (3600.2 - 3600.0);
I expected num to be 0.2, however, it turned out to be 0.1999999999998181. Is there any reason why it is producing a close, but still different decimal?
This is because
doubleis a floating point datatype.If you want greater accuracy you could switch to using
decimalinstead.The literal suffix for
decimalis m, so to usedecimalarithmetic (and produce adecimalresult) you could write your code asNote that there are disadvantages to using a
decimal. It is a 128 bit datatype as opposed to 64 bit which is the size of adouble. This makes it more expensive both in terms of memory and processing. It also has a much smaller range thandouble.