Comparing two strings in Java

I have two lines that I need to compare, but I want to compare them meaningfully so that when they are numbers, their actual value should be compared. So far I have 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 because both of them are converted to doubles.
But this will not work in this case when:

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

Is there any easy way to do this, or do I need to write my own comparator?

+4
source share
4 answers

Instead of using universal, createNumber(String)force them doublewith 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));
}
+3
source

You can use BigDecimalfor this:

final BigDecimal b1 = new BigDecimal(str1);
final BigDecimal b2 = new BigDecimal(str2);
return b1.compareTo(b2) == 0;
+2
source

Double.parseDouble(String). NumberFormatException, , , .

try {
    Double d1 = Double.parseDouble(str1);
    Double d2 = Double.parseDouble(str2);

    //Now you have your doubles
} catch (NumberFormatException e)
{
    //Could not compare as numbers, do something else
}
+2

As indicated in the commentary, one of the lines may be number, and the other is not, or vice versa, or both may be string, therefore, instead of checking whether the lines are numeric lines, I will use a try catchblock.

Like this:

try{
    Double d1 = Double.parseDouble(str1);
    Double d2 = Double.parseDouble(str2);
    System.out.println(d1.equals(d2));
}catch(NumberFormatException ex){

    System.out.println(num1.equals(num2));

}

At first he tries to compare them as numbers, but if at least one of them is not a numeric string, she will depart from comparing the strings in the block catch.

+2
source

Source: https://habr.com/ru/post/1598823/


All Articles