I am developing a program that does some floating point calculations, and I came across an interesting rounding problem in .NET, according to which the expression:
0.1 + 0.2 == 0.3
evaluates to false because:
0.1 + 0.2
matters 0.30000000000000004, not 0.3. This has a very serious effect on unit testing.
I understand why this happens, but I am interested to know: what are the best practices to follow when working with double arithmetic in order to avoid such problems when possible?
EDIT : using type decimaldoesn't help
SUMMARY : I appreciate all for the comments. Unfortunately, some of you have suggested that this question is how to make 0.1 + 0.2 equal to 0.3, and that is not what I asked for. I accept that floating arithmetic can return a value with a change. I asked what general strategy should be followed so that this variation would not cause problems. I think this issue is ready to close.
source
share