4

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.

user2619395
  • 249
  • 1
  • 6
  • 15
  • `10.0.30` is not valid decimal number. You have to either compare them as strings (using custom comparer) or create your own type (class) which would do this. – Zbigniew Jul 25 '13 at 15:30
  • If all you need is to compare version numbers (like "1.0.0.123" and "3.1.1"), try Version class. – S_F Jul 25 '13 at 15:32
  • See [How to compare version numbers](http://stackoverflow.com/questions/7568147/how-to-compare-version-numbers-by-not-using-split-function) – SwDevMan81 Jul 25 '13 at 15:32
  • @walkhard how would one compare them as strings to see if one is less than the other? – user2619395 Jul 25 '13 at 15:36
  • @user2619395 I wasn't clear, I meant that you need to parse strings (e.g. split them by `.` and compare each segment). – Zbigniew Jul 25 '13 at 15:48

2 Answers2

9

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
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
1

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";
Adam Knights
  • 2,141
  • 1
  • 25
  • 48