user3859922
user3859922

Reputation:

How to store BIG int values

What would you use if you had to hold numbers bigger than the ulong type can hold (0 to 18,446,744,073,709,551,615)? For instance measuring distance between planets or galaxies?

Upvotes: 2

Views: 3231

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500065

For values which only require up to 28 digits, you can use System.Decimal. The way it's designed, you don't encounter the scaling issue you do with double, where for large numbers the gap between two adjacent numbers is bigger than 1. Admittedly this looks slightly odd, given that decimal is usually used for non-integer values - but in some cases I think it's a perfectly reasonable use, so long as you document it properly.

For values bigger than that, you can use System.Numerics.BigInteger.

Another alternative is to just use double and accept that you really don't get a precision down to the integer. When it comes to the distance between galaxies, are you really going to have a value which is accurate to a metre anyway? It does depend on how you're going to use this - it can certainly make testing simpler if you use a nicely-predictable integer type, but you should really think about where the values are going to go and what you're going to do with them.

Upvotes: 4

sampathsris
sampathsris

Reputation: 22270

I rather doubt you need to have integer types to store something like the distance between the galaxies. To my knowledge very large integer values are required in few cases like (demonstrative) encryption. For these cases, you can use System.Numerics.BigInteger.

I think you should use floating point types (e.g. double) for purposes like one you described.

Upvotes: 1

Related Questions