Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a string is parsable into Long without try-catch?

Long.parseLong("string") throws an error if string is not parsable into long. Is there a way to validate the string faster than using try-catch? Thanks

like image 970
Serg Avatar asked Apr 01 '10 20:04

Serg


People also ask

How do you check if a string is Parsable?

The NumberUtils. isParsable(String) method checks whether the given String is parsable or not. Parsable numbers are those that are parsed successfully by any parse method like Integer. parseInt(String), Long.

How do you know if a string is Parsable to double?

Therefore, to know whether a particular string is parse-able to double or not, pass it to the parseDouble method and wrap this line with try-catch block. If an exception occurs this indicates that the given String is not pars able to double.


2 Answers

You can create rather complex regular expression but it isn't worth that. Using exceptions here is absolutely normal.

It's natural exceptional situation: you assume that there is an integer in the string but indeed there is something else. Exception should be thrown and handled properly.

If you look inside parseLong code, you'll see that there are many different verifications and operations. If you want to do all that stuff before parsing it'll decrease the performance (if we are talking about parsing millions of numbers because otherwise it doesn't matter). So, the only thing you can do if you really need to improve performance by avoiding exceptions is: copy parseLong implementation to your own function and return NaN instead of throwing exceptions in all correspondent cases.

like image 58
Roman Avatar answered Oct 13 '22 05:10

Roman


From commons-lang StringUtils:

public static boolean isNumeric(String str) {     if (str == null) {         return false;     }     int sz = str.length();     for (int i = 0; i < sz; i++) {         if (Character.isDigit(str.charAt(i)) == false) {             return false;         }     }     return true; } 
like image 30
lexicore Avatar answered Oct 13 '22 07:10

lexicore