【问题标题】:Need to divide a number before parsing it解析前需要除数
【发布时间】:2012-11-30 15:58:48
【问题描述】:

我目前正在从字符串中读取一个长数字。该数字是 3 个整数位,后跟 7 个不带小数点的小数位(例如 1234567890)。

如何在解析前除掉这个数字?

我正在尝试将其解析为整数,但整数的最大值约为 20 亿。

这是我尝试过的:

class Program
{
    static void Main(string[] args)
    {
        using (StreamReader reader = new StreamReader("CLIFF.dat"))
        {
            string line;
            var locations = new Dictionary<string, int[]>() {
                {"210", new [] {405, 4, 128, 12, 141, 12, 247, 15}}, 
                {"310", new [] {321, 4, 112, 12, 125, 12, 230, 15}}, //
                {"410", new [] {477, 4, 112, 12, 125, 12, 360, 15 }} 
            };
 while ((line = reader.ReadLine()) != null)
            {                 
                    var lineStart = line.Substring(0, 3);

                    if (lineStart == "210" || lineStart == "310" || lineStart == "410")
                    {
                        var currentLocations = locations[lineStart];
                        var letters = line.Substring(currentLocations[0], currentLocations[1]);

                        var transactionvolume =
                            int.Parse(line.Substring(currentLocations[2], currentLocations[3])) +
                            int.Parse(line.Substring(currentLocations[4], currentLocations[5]));
                        var watching = line.Substring(currentLocations[6], currentLocations[7]);
                        var number = int.Parse(line.Substring(currentLocations[6], currentLocations[7])*));

是当前位置[6]数太大,需要乘以10^-7。

【问题讨论】:

  • 使用 long.Parse 然后除法。
  • BigInteger 然后除,也许?
  • 两个都试一下,看看我更喜欢哪个,谢谢。
  • @Cylen 好吧,我认为这主要取决于您的数字到底有多大......
  • 或者,使用decimal.Parse从字符串构建一个小数。既然你知道小数点放在哪里,你可以做一些类似decimal.Parse(firstPart + "." + FractionalPart)等的事情。

标签: c# parsing int


【解决方案1】:

可耻地将 cmets 汇总为答案:

问题是 32 位有符号整数最多可以处理 21 亿的值(准确地说是 2,147,483,647)。直接从字符串翻译的值太大。

如 cmets 中所述,可能的策略是:

  • 使用更大的数据类型。 Long、double、decimal、bigint 等都能够处理数百亿或更高的数字(尽管对于浮点类型,它的精度越高,精度越低)。由于您需要浮点类型并且期望小数点后 7 位,因此我个人会选择 Decimal;它是 128 位的最大数据类型,但它具有浮点类型的最佳精度,这意味着您可以期望将任何整数值放入其中,除以 107 并得到正确答案。

  • 分而治之。您已经将数字作为字符串,并且您知道它正好有 7 个小数点。因此,您知道在字符串中放置小数点的位置,以便可以将其解析为浮点类型:

    decimal myValue = decimal.Parse(myString.Substring(0, myString.Length-7) 
                                + "." 
                                + myString.Substring(myString.Length-7, 7));
    

【讨论】:

    【解决方案2】:

    可能是这样的:

    String input = "34567891234567";
    int intPart = int.Parse(input.Substring(0, input.Length - 7));
    int fracPart = int.Parse(input.Substring(input.Length - 7));
    double val = intPart + fracPart * 0.0000001;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多