I’m trying to parse and add 2 numbers together where I don’t know which type they are (int, float, etc.), and I’m trying to store the result in the most appropriate type. For instance, if I get 2 ints, I want the result to be an int, but if I get an int and a double, I want the result to be a double. How would I go about doing this?
One idea that I had was to try parsing as an int first, then long, then float, … to see which type it was. Is there a better way to do this rather than trying/catching the NumberFormatExceptions?
Ex:
String number1 = "5";
String number2 = "3.4";
Object answer = add(number1, number2);
What would add() look like?
I would read the all as a
double, or aBigDecimal. This will be simpler and possibly more efficient than trying to find the “optimal” type.