How do you deal with numbers larger than UInt64 (C#)

30,646

Solution 1

By using a BigInteger class; there's one in the the J# libraries (definitely accessible from C#), another in F# (need to test this one), and there are freestanding implementations such as this one in pure C#.

Solution 2

Can you use the .NET 4.0 beta? If so, you can use BigInteger.

Otherwise, if you're sticking within 28 digits, you can use decimal - but be aware that obviously that's going to perform decimal arithmetic, so you may need to round at various places to compensate.

Solution 3

What is it that you wish to use these numbers for? If you are doing calculations with really big numbers, do you still need the accuracy down to the last digit? If not, you should consider using floating point values instead. They can be huge, the max value for the double type is 1.79769313486231570E+308, (in case you are not used to scientific notation it means 1.79769313486231570 multiplied by 10000000...0000 - 308 zeros).

That should be large enough for most applications

Solution 4

BigInteger represents an arbitrarily large signed integer.

using System.Numerics;

var a = BigInteger.Parse("91389681247993671255432112000000");
var b = new BigInteger(1790322312);
var c = a * b;

Solution 5

Decimal has greater range.

There is support for bigInteger in .NET 4.0 but that is still not out of beta.

Share:
30,646
Alex
Author by

Alex

Updated on July 09, 2022

Comments

  • Alex
    Alex almost 2 years

    In C#, how can one store and calculate with numbers that significantly exceed UInt64's max value (18,446,744,073,709,551,615)?

  • Steve Gilham
    Steve Gilham almost 15 years
    Also worth noting -- there's yet another implementation in the DLR to support Python and Ruby indefinite precision integers, but I haven't looked to see what the public API to that class is.
  • Evan Harper
    Evan Harper almost 12 years
    Amazing that nobody else mentioned this, given that OP didn't specify integers.
  • Anirudha Gupta
    Anirudha Gupta over 6 years
    If anyone has trouble with namespace issue, it's under System.Numerics;
  • Mattias Nordqvist
    Mattias Nordqvist over 4 years
    Pete mentioned this.
  • Stefano
    Stefano about 4 years
    Better yet Int64 myAnswer = 20000L * 1024L * 1024L;
  • Chriss Hd
    Chriss Hd about 4 years
    Sure your can use double to store large numeric values. But some calculations don't work on double the same as the other types. Check: stackoverflow.com/a/906574/5771568