I have a property that returns System.Numerics.BigInteger
. When I casting the property to int, I got this error.
Cannot convert type 'System.Numerics.BigInteger' to 'int'
How can I convert int to/from System.Numerics.BigInteger
in C#?
Use BigInteger. Parse() method. Converts the string representation of a number in a specified style to its BigInteger equivalent. BigInteger bi = 2; for(int i = 0; i < 1234; i++) { bi *= 2; } var myBigIntegerNumber = bi.
BigInteger. intValue() converts this BigInteger to an int. This conversion is analogous to a narrowing primitive conversion from long to int.
BigInt is not the same as INT64 no matter how much they look alike. Part of the reason is that SQL will frequently convert Int/BigInt to Numeric as part of the normal processing. So when it goes to OLE or . NET the required conversion is NUMERIC to INT.
The conversion from BigInteger to Int32 is explicit, so just assigning a BigInteger
variable/property to an int
variable doesn't work:
BigInteger big = ...
int result = big; // compiler error:
// "Cannot implicitly convert type
// 'System.Numerics.BigInteger' to 'int'.
// An explicit conversion exists (are you
// missing a cast?)"
This works (although it might throw an exception at runtime if the value is too large to fit in the int
variable):
BigInteger big = ...
int result = (int)big; // works
Note that, if the BigInteger
value is boxed in an object
, you cannot unbox it and convert it to int
at the same time:
BigInteger original = ...;
object obj = original; // box value
int result = (int)obj; // runtime error
// "Specified cast is not valid."
This works:
BigInteger original = ...;
object obj = original; // box value
BigInteger big = (BigInteger)obj; // unbox value
int result = (int)big; // works
Here are some choices that will convert BigInteger to int
BigInteger bi = someBigInteger;
int i = (int)bi;
int y = Int32.Parse(bi.ToString());
Watch Out though if the BigInteger value is too large it will throw a new exception so maybe do
int x;
bool result = int.TryParse(bi.ToString(), out x);
Or
try
{
int z = (int)bi;
}
catch (OverflowException ex)
{
Console.WriteLine(ex);
}
Or
int t = 0;
if (bi > int.MaxValue || bi < int.MinValue)
{
Console.WriteLine("Oh Noes are ahead");
}
else
{
t = (int)bi;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With