Posts tagged ‘Decimal’

## When not to use the Double Type in .Net : Financial Calculations!

Most developers, myself included, have fallen into the trap of using the double or float type when doing financial calculations and have discovered that values get out of sync with the balance sheet pretty quick. The short answer is to always use the precise type of decimal to do calculations and avoid double and float. For example take this snippet of code:

`double n1 = 1134.266;`
`double n2 = 1134.0;`

`double result1 = n1 - n2;`

`Console.WriteLine(result1.ToString()); // Result: 0.266000000000076`

Where did the extra 76 come in? Using decimal will fix that issue. The failure of double comes into play when thinking of fractions such as 1/3 + 1/3 + 1/3 which we all learned in grammar schools is 1. When that is represented as .3333 + .3333 + .3333 … well that equals .9999 which is not 1. Do you want to be on the losing end of that financial calculation everytime you withdrawal money from your bank?

So in the future when should one use the appropriate non integer type?

• Decimal for Financial calculations when exactness in calculations is needed.
• Float is used for scientific calculations when range is more important than precision up to seven significant digits.
• Double to be used when the float range of seven significant figures fails and the need up to sixteen significant digits is needed.