C# Professional - Numbers

talent-agile
68K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Precision & Rounding

Due to the internal representation of float and 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.

  • float and double types are meant to use when performance is more important than precision.
  • decimal is 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 decimal type (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 decimal.

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.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content