c# - 如何将长字符串数值转换为整数

标签 c# integer long-integer converters int32

我必须使用ToInt32,将长字符串数值“10000000001”转换为整数,因此这种方式仅限于十位数字:

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

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

    int c = a + b;

    Console.WriteLine(c);

结果:

2000000000

但是如果字符串数值大于十位数如何转换:

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

获取结果:

20000000002

最佳答案

如果该值可以是任意数字,因为它可以与您能想到的任何数字一样大或小,则使用 System.Numerics 命名空间中的 BigInteger 结构。

示例:

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

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

基本上,BigInteger 没有上限或下限。唯一的限制是你的 RAM。

但是,如果您的数字稍微超过 10 位,那么您最好使用 int64。长数据类型。

关于c# - 如何将长字符串数值转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42238158/

相关文章:

Python 作业 - 没有意义

java - 从一个文件中获取整数列表

java - double 到 long 无需在 Java 中进行转换

C# 在控制台应用程序中嵌入测试代码

c# - 通过完成的事务连接两个表

c# - 如果母版页使用 css 文件,其他文件是否也可以使用该 css 文件?

c++ - 选择哈希键类型的理由

C:U64和uint64_t之间的区别

java.lang.ClassCastException : java. math.BigInteger 无法转换为 java.lang.Long

c# - VSTS - Visual Studio 测试任务失败并显示错误 No Test is available