Android compare values with multiple decimal points

I want to check application versions to implement a force update feature from the server. I want to check values such as 1.1.5, 1.1.6 to see which is greater, I am getting this values as a string from the server and I'm getting a number format exception parsing that string to a float value before being able to compare. Here is my code:

String server_app_version = versionObj.getString("android");
String  version = info.versionName;    
float server_version = Float.parseFloat(server_app_version);
float current_version = Float.parseFloat(version);

How can i compare if server_version > current_version ?

4 answers

  • answered 2017-10-11 10:20 Gerard

    Split the string by the '.' and cast and compare numbers from left to right

  • answered 2017-10-11 10:20 Avinash Ajay Pandey

    try this method.

      public static int versionCompare(String str1, String str2) {
        String[] vals1 = str1.split("\\.");
        String[] vals2 = str2.split("\\.");
        int i = 0;
        // set index to first non-equal ordinal or length of shortest version string
        while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {
          i++;
        }
        // compare first non-equal ordinal number
        if (i < vals1.length && i < vals2.length) {
            int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));
            return Integer.signum(diff);
        }
        // the strings are equal or one string is a substring of the other
        // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4"
        return Integer.signum(vals1.length - vals2.length);
    }
    

    Alex Gitelman answers

  • answered 2017-10-11 10:20 Juan

    try this aproach:

     var firstInput = "1.1.5";
    var secondInput = "1.1.6";
    
    var firstValues = firstInput.Split('.');
    var secondValues = secondInput.Split('.');
    
    // And then you compare one by une using a for loop
     // if Convert.ToInt32(firstValues[i]) >= Convert.ToInt32(secondsValues[i])
    // Your logic is there
    

    I hope it helps.

    Juan

  • answered 2017-10-11 10:20 Samir Bhatt

    Try this. it may help you.

    Scanner s1 = new Scanner(str1);
    Scanner s2 = new Scanner(str2);
    s1.useDelimiter("\\.");
    s2.useDelimiter("\\.");
    
    while(s1.hasNextInt() && s2.hasNextInt()) {
        int v1 = s1.nextInt();
        int v2 = s2.nextInt();
        if(v1 < v2) {
            return -1;
        } else if(v1 > v2) {
            return 1;
        }
    }
    
    if(s1.hasNextInt()) return 1; //str1 has an additional lower-level version number
    return 0;