#80 – Use Decimal Type for Monetary Calculations

Since floating point numbers are stored as a binary data, most floating point numbers cannot be stored exactly and suffer from round-off error–the difference between the true mathematical value and the value being stored digitally.

Because of how floating point numbers are stored, even simple base-10 numbers with not much precision cannot be represented exactly.  Consider the example below:

 float f1 = 0.1f;
 float error = (f1 * 1000.0f) - 100.0f;  // Error is 1.49e-6

This demonstrates that we weren’t able to store exactly the value of 0.1, but the value nearest to 0.1 that was representable using the float type.

This inaccuracy leads to errors when we try to store values representing financial transactions and perform simple mathematical operations on the values.  Because of this, you should always use the decimal type for storing financial data:

 decimal f1 = 0.1m;
 decimal error = (f1 * 999999999.0m) - 99999999.9m;  // Error still 0