当有数千个时,将字符串转换为double

问题描述 投票:-3回答:2

我正在尝试将字符串转换为double(然后转换为int),但它会引发异常。我的程序很旧,我不确定是不是这样。当我在Visual Studio 2017上测试它时,它似乎工作?

   string line = "11-03-1-01   |   1 | 5 000,00|1054 |P:1|KP:|RB:"; 

    private static int GetCount(string line)
    {
        var splittedLine = line.Split('|');
        var lineWithReplacedDot = splittedLine[2].Replace('.', ',');
        var lineWithSpacesRemoved = lineWithReplacedDot.Replace(" ", "");
        var additionalSpacesRemoved = lineWithSpacesRemoved.Trim();
        var parsedToDouble = Double.Parse(additionalSpacesRemoved);
        var parsedToInteger = (int)parsedToDouble;

        return parsedToInteger;

    }

当我在我的旧程序上执行它时,它会在尝试执行Double.Parse(additionalSpacesRemoved)时引发Format Exception。似乎它没有消除5到000之间的空间。

我也尝试过Convert.ToDouble(additionalSpacesRemoved)但它没有帮助。还有其他方法吗?

我想结果达到“5000”。

c# parsing double
2个回答
0
投票

看起来你想把|分隔的第三个字符串作为int

你的代码几乎是对的。你刚才颠倒了'.', ','论证的顺序。他们应该是',', '.'。您想要替换的角色首先出现。这是一些有效的代码:

private static int GetCount(string line)
{
    return (int)Convert.ToDouble(
        line.Split('|')[2]
            .Replace(" ", "")
            .Replace(',', '.'));
}

0
投票

试试这个

static void Main(string[] args)
{
    string line = "11-03-1-01   |   1 | 5 000,00|1054 |P:1|KP:|RB:";
    Debug.WriteLine(GetCount(line));
    // 5000
}

public static int GetCount(string line)
{
    var parts = line.Split('|');
    var text = parts[2].Trim();

    var style = new NumberFormatInfo()
    {
        NumberDecimalSeparator=",",
        NumberGroupSeparator=" "
    };

    if (decimal.TryParse(text,
        NumberStyles.Float | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, 
        style, out decimal result))
    {
        return (int)result;
    }

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.