简体   繁体   中英

How to convert long string number value into integer

what I have to use instead ToInt32 , to convert long string number value "10000000001" into integer, so this way is limited to a ten-digit number:

    string str1 = "1000000000";
    string str2 = "1000000000";

    int a = Convert.ToInt32(str1);
    int b = Convert.ToInt32(str2);

    int c = a + b;

    Console.WriteLine(c);

result:

2000000000

but how to convert if string number value is larger then ten-digit number:

    string str1 = "10000000001";
    string str2 = "10000000001";

to get result:

20000000002

if the value could be an arbitrary number as in it could be as large or small as any number you can think of then use BigInteger struct which is found in the System.Numerics namespace.

example:

   string str1 = "1000023432432432432234234324234324432432432432400000";
   string str2 = "1003240032432432423432432948320849329493294832800000";

   BigInteger BigInt = (BigInteger.Parse(str1) + BigInteger.Parse(str2)); // might want to validate before doing this.
   Console.WriteLine(BigInt);

Basically, BigInteger has no upper bound or lower bound limit. the only limit to it is your RAM.

However, if your number will be going above 10 digits by little amount then you might as well use int64. the long data type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM