Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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

like image 880
user978122 Avatar asked Mar 21 '26 14:03

user978122


1 Answers

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).

like image 96
Jon Skeet Avatar answered Mar 23 '26 04:03

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!