Real Types with Decimal Precision

Real Types with Decimal Precision


C# supports the so-called decimal floating-point arithmetic, where numbers are represented via the decimal numeral system rather than the binary one. Thus, the decimal floating point-arithmetic type in C# does not lose accuracy when storing and processing floating-point numbers.
The type of data for real numbers with decimal precision in C# is the 128-bit type decimal. It has a precision from 28 to 29 decimal places. Its minimal value is -7.9×1028 and its maximum value is +7.9×1028. The default value is 0.0m or 0.0M. The 'm' character at the end indicates explicitly that the number is of type decimal (because by default all real numbers are of type double). The closest to 0 numbers, which can be recorded in decimal, are ±1.0 × 10-28. It is obvious that decimal can store neither very big positive or negative numbers (for example, with hundreds of digits), nor values very close to 0. However, this type is almost perfect for financial calculations because it represents the numbers as a sum of powers of 10 and losses from rounding are much smaller than when using binary representation. The real numbers of type decimal are extremely convenient for financial calculations – calculation of revenues, duties, taxes, interests, payments, etc.
Here is an example in which we declare a variable of type decimal and assign its value:


The number decimalPI, which we declared of type decimal, is not rounded even with a single position because we use it with precision of 21 digits, which fits in the type decimal without being rounded.
Because of the high precision and the absence of anomalies during calculations (which exist for float and double), the decimal type is extremely suitable for financial calculations where accuracy is critical.  

The main difference between real floating-point numbers and real numbers with decimal precision is the accuracy of calculations and the extent to which they round up the stored values. The double type allows us to work with very large values and values very close to zero but at the expense of accuracy and some unpleasant rounding errors. The decimal type has smaller range but ensures greater accuracy in computation, as well as absence of anomalies with the decimal numbers.
If you perform calculations with money use the decimal type instead of float or double. Otherwise, you may encounter unpleasant anomalies while calculating and errors as a result!
As all calculations with data of type decimal are done completely by software, rather than directly at a low microprocessor level, the calculations of this type are from several tens to hundreds of times slower than the same calculations with double, so use this type only when it is really necessary.

Post a Comment

0 Comments