BigInteger
Occasionally large integers are needed in VB.NET programs, even ones that exceed the maximum value of a double
. BigInteger
can accommodate these values.
By calling New, we can create a BigInteger
from a Double
. And with Add()
we combine two BigIntegers
and receive another BigInteger
. We call ToString()
to convert a BigInteger
to a String
.
To create a BigInteger
, we need to call the New Function, which is the constructor. We can pass a value like a Double
to the New Function.
BigIntegers
needed for the code example from the Double.MaxValue
constant.BigInteger
Class
has a Shared Add()
Function on it, and this function adds its two arguments together.string
interpolation to print out the values. We have doubled the Double.MaxValue
, which would not fit inside an actual Double
.BigInteger
can contain 309 digits, and even more, without issues. This is truly a large numeric type.Imports System.Numerics Module Module1 Sub Main() ' Step 1: create 2 BigIntegers, based on double.MaxValue. Dim big1 As BigInteger = New BigInteger(Double.MaxValue) Dim big2 As BigInteger = New BigInteger(Double.MaxValue) ' Step 2: call Add() to add the BigIntegers. Dim result As BigInteger = BigInteger.Add(big1, big2) ' Step 3: print out the values. Console.WriteLine($"DOUBLE MAX: {big1}") Console.WriteLine($"DOUBLE MAX * 2: {result}") ' Step 4: print the digit count of the BigInteger. Console.WriteLine($"DIGITS: {result.ToString().Length}") End Sub End ModuleDOUBLE MAX: 179769313486...50404026184124858368 DOUBLE MAX * 2: 359538626972...500808052368249716736 DIGITS: 309
When a Double
is not enough for a certain numeric type, consider the BigInteger
type, which can handle much larger numbers. It is not going to help performance if used extensively in hot loops.