How to Parse a String with Multiple Decimal Points

2019-06-25 01:21发布

问题:

I was wanting to parse a string such as "10.0.20" into a number in order to compare another string with the same format in C#.net

For example I would be comparing these two numbers to see which is lesser than the other: if (10.0.30 < 10.0.30) ....

I am not sure which parsing method I should use for this, as decimal.Parse(string) didn't work in this case.

Thanks for your time.

Edit: @Romoku answered my question I never knew there was a Version class, it's exactly what I needed. Well TIL. Thanks everyone, I would have spent hours digging through forms if it wasn't for you lot.

回答1:

The the string you're trying to parse looks like a verson, so try using the Version class.

var prevVersion = Version.Parse("10.0.20");
var currentVersion = Version.Parse("10.0.30");

var result = prevVersion < currentVersion;
Console.WriteLine(result); // true


回答2:

Version looks like the easiest way, however, if you need unlimited 'decimal places' then try the below

private int multiDecCompare(string str1, string str2)
    {
        try
        {
            string[] split1 = str1.Split('.');
            string[] split2 = str2.Split('.');

            if (split1.Length != split2.Length)
                return -99;

            for (int i = 0; i < split1.Length; i++)
            {
                if (Int32.Parse(split1[i]) > Int32.Parse(split2[i]))
                    return 1;

                if (Int32.Parse(split1[i]) < Int32.Parse(split2[i]))
                    return -1;
            }

            return 0;
        }
        catch
        {
            return -99;
        }
    }

Returns 1 if first string greater going from left to right, -1 if string 2, 0 if equal and -99 for an error.

So would return 1 for

string str1 = "11.30.42.29.66";
string str2 = "11.30.30.10.88";