Skip to content
Advertisement

Is there any better option for checkin if a substring is numeric?

I am trying to parse a long string. In the string, there are numbers and other kinds of symbols (text). I need to store the words and numbers separately. Firstly, I have the string split by spaces.

String fullString = "Some 3 random 5.6 text 12 with -4.5 numbers -1 in 0 beetween";
String [] words = fullString.split(" ");

I’ve made a method to check if the method Double.parseDouble() trows and exception on each substring stored in words variable.

private static boolean isNumeric(String str) {
    if (str == null) {
       return false;
    }
    try {
       double parseDouble = Double.parseDouble(str);
    } catch (NumberFormatException numberFormatException) {
       return false;
    }
    return true;
}

In my code, when I get a true I will have to run twice the method Double.parseDouble(str).

for(String word: words){
    if(isNumeric(word)){
        numbers.push = Double.parseDouble(word);
    }
}

I think I am looking for any of these two options:

  1. An easier method to check if the substring stored in words is a number.
  2. Another way to parse the double just once.

Advertisement

Answer

In your case if using Double.parseDouble() is a good enough indicator if the String is numeric or not, and you just want to avoid running the same method twice, once for validation and once for actual parsing than you can use MgntUtils Open source library that has the following method in class TextUtils:

public static double parseStringToDouble(java.lang.CharSequence num,
                                         double defaultValue)

You can use it in such a way:

Double num = TextUtils.parseStringToDouble(parsedStr, Double.MIN_VALUE);
if(Double.MIN_VALUE.equals(num)) {
  treatStringAsNotNumeric(parsedStr);
} else {
  treatStringAsNumeric(num /* or may be parsedStr*/);
}

The library is available as a Maven artifact and on Github (Including source code and Javadoc). Javadoc online also available here

Disclaimer: The library is written by me

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement