java – Is it possible to compare numeric values ​​to strings without casting to type Number?

Question:

I have two numeric values ​​that are retrieved into strings, and I'd like to know if there's a way to compare them to see which numeric value is larger, but without having to do conversion to Number type (like Integer , Double and Float ).

Example:

String strValue01 = "50";
String strValue02 = "62";

Is there any way to compare which number is larger without having to parse the numeric type ? I thought there might be something via ASCII values, but I have no idea how to do it, if at all possible.

Answer:

This should work:

public static int seuComparador(String a, String b) {
    String c = a;
    String d = b;
    while (c.length() < d.length()) c = "0" + c;
    while (c.length() > d.length()) d = "0" + d;
    return c.compareTo(d);
}

Here's a test:

public static void main(String[] args) {
    System.out.println(seuComparador("0", "3"));
    System.out.println(seuComparador("10", "3"));
    System.out.println(seuComparador("007", "300"));
    System.out.println(seuComparador("40", "040"));
}

Here's the output:

-3
1
-3
0

It works according to the principle of the java.util.Comparator interface. Where:

  • A return of zero means equal strings.
  • A negative number is when the first one precedes the second.
  • A positive number is when the first succeeds the second.

That is, this output means 0 is less than 3, 10 is greater than 3, 007 is less than 300, and 40 is equal to 040.

See here working on ideone.


However, this code is not very efficient as it creates several temporary intermediate objects to add zeros. An optimization that already creates all the necessary zeros once is possible. It is also possible to proceed directly to compareTo when the sizes of String s are equal:

public static int seuComparador(String a, String b) {
    int sa = a.length();
    int sb = b.length();
    if (sa == sb) return a.compareTo(b);
    int dif = sa > sb ? sa - sb : sb - sa;

    StringBuilder pad = new StringBuilder(sa > sb ? sa : sb);
    for (int i = 0; i < dif; i++) {
        pad.append('0');
    }

    String c = sa > sb ? a : pad.append(a).toString();
    String d = sa > sb ? pad.append(b).toString() : b;
    return c.compareTo(d);
}

Produces the same output as the previous one. See here working on ideone.

Scroll to Top