You can convert a numeric string to various Java numeric types as follows:
String to int:
String number = "12";
int num = Integer.parseInt(number);
String to float:
String number = "12.0";
float num = Float.parseFloat(number);
String to double:
String double = "1.47";
double num = Double.parseDouble(double);
String to boolean:
String falseString = "False";
boolean falseBool = Boolean.parseBoolean(falseString); // falseBool = false
String trueString = "True";
boolean trueBool = Boolean.parseBoolean(trueString); // trueBool = true
String to long:
String number = "47";
long num = Long.parseLong(number);
String to BigInteger:
String bigNumber = "21";
BigInteger reallyBig = new BigInteger(bigNumber);
String to BigDecimal:
String bigFraction = "17.21455";
BigDecimal reallyBig = new BigDecimal(bigFraction);
Conversion Exceptions:
The numeric conversions above will all throw an (unchecked) NumberFormatException
if you attempt to parse a string that is not a suitably formatted number, or is out of range for the target type. The Exceptions topic discusses how to deal with such exceptions.
If you wanted to test that you can parse a string, you could implement a tryParse...
method like this:
boolean tryParseInt (String value) {
try {
String somechar = Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
However, calling this tryParse...
method immediately before parsing is (arguably) poor practice. It would be better to just call the parse...
method and deal with the exception.