What kind of data (double, float or decimal) should I use to represent currency in . NET with C#?

Asked

Viewed 25,606 times

20

Although I am aware of what would be better to use, I ask this question for educational purposes since I see several examples of people using double in C#. But I’ve had problems with double for coin calculations and read in several places that the type loses precision in some cases.

Therefore, in which situations it would be better to use each type?

2 answers

28


The Decimal is the ideal type for calculating values. It has an enormous amplitude (79,228,162,514,264,337,593,543,950,335 up to -79,228,162,514,264,337,593,543,950,335) and has one of the smallest error margins for rounding.

Double is more suitable for general scientific calculations, where the margin of error is not negligible, but is tolerable. Despite having a larger range of values, the calculation of mantissa and characteristic produces known rounding problems.

Float is a Double with fewer bytes for representation, therefore, with a small amplitude of values and accuracy and rounding problems similar to the Double.

14

The most appropriate is decimal, according to MSDN itself:

Compared to floating point types, the decimal type has more precision and a short break, which makes it appropriate for financial and monetary calculations.

It has 28-29 digit accuracy, enough not to affect the pennies with calculations.

The double is 15-16, and the float only 7 digits of accuracy.


The observation is that if no precise calculations are made in the system, could be used float since it occupies only 32-bits (against 128 of decimal). But in practice this does not pose a problem unless you will have a large array of decimals, for example.

In this case, you should determine whether you care about more good space usage practice or the consistency of all monetary variables being typed as decimal in your code (good programming practice).

  • Decimal type accuracy is 28-29 significant digits.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.