Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two strings meaningfully in Java

I've two strings which I need to compare, but I want to compare them meaningfully such that when they are numbers their actual value should be compared. So far I've tried the following solution:

String str1 = "-0.6";
String str2 = "-.6";
if (NumberUtils.isNumber(str1) && NumberUtils.isNumber(str2)) {
    Number num1 = NumberUtils.createNumber(str1);
    Number num2 = NumberUtils.createNumber(str2);
    System.out.println(num1.equals(num2));
} else {
    System.out.println(str1.equals(str2));
}

This works as both are converted to doubles.
But this won't work in this case where:

String str1 = "6";
String str2 = "6.0";

Is there any easy way to do this, or will I have to write my own Comparator?

like image 210
Heisenberg Avatar asked Jan 08 '23 22:01

Heisenberg


2 Answers

Instead of using the general-purpose createNumber(String), force them to doubles using createDouble(String):

String str1 = "-0.6";
String str2 = "-.6";
if (NumberUtils.isNumber(str1) && NumberUtils.isNumber(str2)) {
    Double d1 = NumberUtils.createDouble(str1);
    Double d2 = NumberUtils.createDouble(str2);
    System.out.println(d1.equals(d2));
} else {
    System.out.println(str1.equals(str2));
}
like image 125
Mureinik Avatar answered Jan 19 '23 02:01

Mureinik


You can probably use BigDecimal for this:

final BigDecimal b1 = new BigDecimal(str1);
final BigDecimal b2 = new BigDecimal(str2);
return b1.compareTo(b2) == 0;
like image 23
fge Avatar answered Jan 19 '23 02:01

fge