user978122
user978122

Reputation: 5761

C#: Decimal -> Largest integer that can be stored exactly

I've been looking at the decimal type for some possible programming fun in the near future, and would like to use it a a bigger integer than an Int64. One key point is that I need to find out the largest integer that I can store safely into the decimal (without losing precision); I say this, because apparently it uses some floating point in there, and as programmers, we all know the love that only floating point can give us.

So, does anyone know the largest int I can shove in there?

And on a separate note, does anyone have any experience playing with arrays of longs / ints? It's for the project following this one.

Thanks, -R

Upvotes: 2

Views: 6484

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1501043

decimal works differently to float and double - it always has enough information to store as far as integer precision, as the maximum exponent is 28 and it has 28-29 digits of precision. You may be interested in my articles on decimal floating point and binary floating point on .NET to look at the differences more closely.

So you can store any integer in the range [decimal.MinValue, decimal.MaxValue] without losing any precision.

If you want a wider range than that, you should use BigInteger as Fredrik mentioned (assuming you're on .NET 4, of course... I believe there are 3rd party versions available for earlier versions of .NET).

Upvotes: 9

Fredrik Mörk
Fredrik Mörk

Reputation: 158319

If you want to deal with big integers, you might want to look into the BigInteger type.

From the documentation:

Represents an arbitrarily large signed integer

Upvotes: 3

Related Questions