【问题标题】:How to convert long string number value into integer如何将长字符串数值转换为整数
【发布时间】:2017-02-14 23:31:28
【问题描述】:

我必须改用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

【问题讨论】:

    标签: c# integer long-integer converters int32


    【解决方案1】:

    如果该值可以是任意数字,因为它可以与您能想到的任何数字一样大或小,则使用 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 没有上限或下限。唯一的限制是你的内存。

    但是,如果您的号码会稍微超过 10 位,那么您不妨使用 int64。长数据类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 2011-06-26
      • 2022-01-09
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      相关资源
      最近更新 更多