0

I have come across an issue that I can't seem to find any answers for. I have a number as a string in the format "5.2.3" what format would I convert this into to be able to use the greater than and less than operators in C#? I have tried the following which errors:

Decimal version = Decimal.Parse(strVersion);
if (version < Decimal.Parse("5.2.4"))
{
     // Do something
}

The decimal type which essentially this number is gives me the error "Invalid Format Exception"?

Apqu
  • 4,880
  • 8
  • 42
  • 68

3 Answers3

7

I guess you want to compare the versions.

You can use System.Version for that

Try below sample code as answered here Compare version numbers without using split function

string v1 = "1.23.56.1487";
        string v2 = "1.24.55.487";

        var version1 = new Version(v1);
        var version2 = new Version(v2);

        var result = version1.CompareTo(version2);
        if (result > 0)
            Console.WriteLine("version1 is greater");
        else if (result < 0)
            Console.WriteLine("version2 is greater");
        else
            Console.WriteLine("versions are equal");
        return;
Community
  • 1
  • 1
Neel
  • 11,625
  • 3
  • 43
  • 61
6

Have you looked at System.Version? Your variable name seems to indicate that you're looking at a version number anyway, and the class provides comparison operators.

pmcoltrane
  • 3,052
  • 1
  • 24
  • 30
0

use Version

string n1 = "5.2.4";
string n2 = "5.3.4";

Version v1 = new Version(n1);
Version v2 = new Version(n2);

int result = v1.CompareTo(v2);

if (result > 0)
{
    //greater than v1
}
else if (result < 0)
{
    //2 is greater
}
else
{
    //they are equal
}
Tsukasa
  • 6,342
  • 16
  • 64
  • 96