How to parse a string with multiple decimal points

I wanted to parse a string like "10.0.20" into a number to compare another string with the same format in C # .net

For example, I would compare these two numbers to see which is less than the other: if (10.0.30 <10.0.30) ....

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

Thank you for your time.

Edit: @ Romoku answered my question, I never knew that there is a version class, this is exactly what I need. Good til. Thanks to everyone, I would spend hours digging through forms if it weren’t for you a lot.

+4
source share
2 answers

The line you are trying to parse looks like 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 
+7
source

The version looks like the easiest way, however, if you need unlimited "decimal places", try 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 the first line goes more from left to right, -1 if the line is 2, 0 if it is equal, and -99 for an error.

So, return 1 for

 string str1 = "11.30.42.29.66"; string str2 = "11.30.30.10.88"; 
+1
source

Source: https://habr.com/ru/post/1493470/


All Articles