Precision & Rounding
Due to the internal representation of
double numeric types, arithmetic operations on these types can result in imprecise results, which will be rounded to the nearest representable value.
When using non-integer numeric types in C#, it is important to know the pros and cons of each specific type.
doubletypes are meant to use when performance is more important than precision.
decimalis instead more accurate than the two others, at the cost of performance. When doing arithmetic operations that require a high precision in results without roundings, make sure you use the
decimaltype (this is even more important when doing calculation about money or finance).
If we use the
decimal type for the same operation that above, the result is correct.
Keep in mind that the rounding precision issue is still after a high number of decimal part digits. If you need to calculate values for financial usage with multiple arithmetic operations, you can consider using
double type for intermediary arithmetic operations, round the result to an appropriate number of digits and convert it to a
This will give you the best compromise between performance and precision, and it is often precise enough for financial applications.
In the following example, you can see that there is a precision difference between the rate calculated from
double types and the
decimal types. However, the difference in the calculation result only appears at the 12th decimal digit.