This is often quite obvious that when we are developing application which operates on a real numbers we use a double data type in .net. Here you will see why you should take a special care about the floating point calculations in your software.
Generally all floating point calculation problems comes from the fact that many real number does not have an exact representation in floating point arithmetic. For those who want to dig into this quite difficult topic here is some guide What Every Computer Scientist Should Know About Floating-Point Arithmetic which is part of even larger guide Numerical Computation Guide.
In .net we have a double data type which is the preferred type for real number operations. In the definition in msdn you will find a information that for instance number 1/10 does not have a exact representation in binary format and operations performed on this value may involve some inaccuracy.
Let’s see how it looks like:
we know that the result should be 0.01 while the calculated result is
Things are also bad if we simply add double numbers. Let’s add 1/10 ten times, so we expect to have whole one. What is calculated by floating point arithmetic?
What is the solution for such problems? Well there is no ideal solution. One option is to round the result of each operation that involves double numbers. However we need to know what accuracy is enough for our purpose and use a appropriate number of decimal places rounding. Assume we are fine with 3 decimal places accuracy we get then
and we get 1 as a result. Same works with multiplication.
Another option available in .net is the decimal data type. This is a recommended solution for financial and banking applications, provides more accuracy and mitigates the rounding errors. However it does not solve the problem at all, just pushes it further on the accuracy line.