Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Parse a String with Multiple Decimal Points

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.

like image 976
user2619395 Avatar asked Dec 25 '22 23:12

user2619395


2 Answers

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
like image 74
Dustin Kingen Avatar answered Jan 12 '23 17:01

Dustin Kingen


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";
like image 30
Adam Knights Avatar answered Jan 12 '23 17:01

Adam Knights