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.

5
  • 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. Commented Jul 25, 2013 at 15:30
  • If all you need is to compare version numbers (like "1.0.0.123" and "3.1.1"), try Version class. Commented Jul 25, 2013 at 15:32
  • See How to compare version numbers Commented Jul 25, 2013 at 15:32
  • @walkhard how would one compare them as strings to see if one is less than the other? Commented Jul 25, 2013 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). Commented Jul 25, 2013 at 15:48

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.