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.
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
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With