I am trying to write a method that takes in a String
and returns an Object
. The catch is I want to parse it to one of a few different data-types, and if that fails, return the original String
. I currently have the code below. Is this the best way to handle what I want or is there something obvious that I'm missing?
private static Object tryParse(String str) {
try {
return Long.parseLong(str);
} catch (NumberFormatException ex1) {
try {
return Double.parseDouble(str);
} catch (NumberFormatException ex2) {
return str;
}
}
}
EDIT: I made a tweak that I think should improve performance a bit since I only need to check for longs, doubles, and Strings.
private static Object tryParse(String str) {
try {
Double d = Double.parseDouble(str);
if (d % 1 == 0) {
return d.longValue();
}
return d;
} catch (NumberFormatException ex1) {
return str;
}
}
"1e30"
, which is an integer number, but too large forlong
. \$\endgroup\$