Search code examples
javaversionbigdecimal

Comparing of version in Java


I have a function that compares Eclipse versions. We substring the current Eclipse IDE (example if the current version is 4.7.10, the function will return 4.7)

My problem is the current version right now is 4.10. What Java does when comparing BigDecimal it is removes the trailing zeros.

How do I get that 4.10 will be greater than 4.5?

Thank you!


Solution

  • Here is something to get you going - very simplistic:

    public class Main {
        public static void main(String[] args)
        {
    
            String version1 = "4.10";
            String version2 = "4.5";
    
            compareVersions(version1, version2);
        }
    
        private static void compareVersions(String v1, String v2) {
            String[] versionSplit1 = v1.split("\\.");
            String[] versionSplit2 = v2.split("\\.");
            if (versionSplit1[0].equals(versionSplit2[0])) {
                if (Integer.parseInt(versionSplit1[1]) > (Integer.parseInt(versionSplit2[1]))) {
                    System.out.println(v1 + " is bigger than " + v2);
                } else if (Integer.parseInt(versionSplit1[1]) == (Integer.parseInt(versionSplit2[1]))){
                    System.out.println(v1 + " is equal to " + v2);
                } else {
                    System.out.println(v2 +  " is bigger than " + v1);
                }
            } else if (Integer.parseInt(versionSplit1[0]) > Integer.parseInt(versionSplit2[0])) {
                System.out.println(v1 + " is bigger than " + v2);
            } else {
                System.out.println(v2 + " is bigger than " + v1);
            }
        }
    }
    

    Here's a very quick rough solution if I understand your problem correctly - I imagine you will need to extend this to suit your needs, but the idea stays.

    1. Convert your version into a String if it still isn't.
    2. Split by dot, you end up with two parts - e.g. the first part (4) and second part (10).
    3. Compare the first part (since it is a String, you will need to parse it to an Integer). If the first part is the same, compare the second part (you will need to parse it as well).

    If you are using BigDecimal and you want to convert to String and keep the trailing zero's, try this:

    double value = 4.10;
    //convert double to BigDecimal
    BigDecimal bigDecimalValue = BigDecimal.valueOf(value);
    BigDecimal tempValue = bigDecimalValue.setScale(2, RoundingMode.CEILING);
    //convert to String
    System.out.println(tempValue.toPlainString()); //5.40
    

    Then proceed as described with Strings above.