2

I read that the Decimal type has a range of (-7.9 x 10^28 to 7.9 x 10^28) / (10^0 to 10^28) and that it is "appropriate for financial and monetary calculations."

I can't seem to find a source that says that Decimal can represent to the penny all values from ($79,000,000,000,000,000,000,000,000,000.00) to $79,000,000,000,000,000,000,000,000,000.00.

Decimal is a 128-bit type, and 128-bits could represent every penny from -10^38 to 10^38. But I don't know how Decimal is implemented, so as with floats there could be penny precision loss the further the number goes from 0.

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • 7
    The rounding errors caused by Decimals are directly transferred to Bill Gate's private banking account. – Fabian Bigler Jul 15 '14 at 16:04
  • 1
    Keep in mind that if you want to keep accuracy _to the penny_ then your "maximim" value is really `Decimal.MaxValue / 100` – D Stanley Jul 15 '14 at 16:10

2 Answers2

6

Decimal C# - MSDN

The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations that require large numbers of significant integral and fractional digits and no round-off errors. The Decimal type does not eliminate the need for rounding. Rather, it minimizes errors due to rounding.

For more info you may see Decimal floating point in .NET by Jon Skeet

Habib
  • 219,104
  • 29
  • 407
  • 436
  • 1
    Nice answer. Just adding this for more info: http://csharpindepth.com/articles/general/decimal.aspx – Cory Jul 15 '14 at 16:09
  • If Decimal is not enough accurate (I very much doubt it...) then you can also have a look at this: http://stackoverflow.com/questions/2863388/what-is-the-equivalent-of-the-java-bigdecimal-class-in-c – Fabian Bigler Jul 15 '14 at 16:26
1

I can't seem to find a source that says that Decimal can represent to the penny all values from ($79,000,000,000,000,000,000,000,000,000.00) to $79,000,000,000,000,000,000,000,000,000.00.

That's because it can't. decimal allows up to 29 significant digits of precision. That means if you want to maintain accuracy to the penny, then your maximum safe value is really (Decimal.MaxValue -1)/100 (or $792,281,625,142,643,375,935,439,503.30:

(Decimal.MaxValue - (Decimal.MaxValue - 0.01m))                  == 0
(Decimal.MaxValue/100- (Decimal.MaxValue/100 - 0.01m))           == 0  // why?
(((Decimal.MaxValue-1)/100)- ((Decimal.MaxValue-1)/100 - 0.01m)) == 0.01

Note: I'm not certain why Decimal.MaxValue/100 doesn't work, but if Decimal.MaxValue - 1 is a safe limit then you should be fine.

D Stanley
  • 149,601
  • 11
  • 178
  • 240