Java: Converting Strings to Numbers

Java: Converting Strings to Numbers

To convert a string value to a number
(for example, to convert the String value in a text field to an int),
use these methods. Assume the following declarations:

String s; int i;  long l;  float f;  double d;

typeExample statement
int
i = Integer.parseInt(s);
long
l = Long.parseLong(s);
float
f = Float.parseFloat(s);
double
d = Double.parseDouble(s);

If s is null or not a valid representation of a number of that type, these
methods will throw (generate) a NumberFormatException.
See below.

Handling NumberFormatExceptions

Put number conversions inside a try . . . catch
statement so that you can do something if bad input is entered.
The conversion method will throw a NumberFormatException when there is bad input.
Catch the NumberFormatException, and do something to handle this
error condition. Put your conversion in the try clause,
and the error handling in the catch clause. Here is an example
of the kind of utility function you might write to do this checking.

//--- Utility function to get int using a dialog.
public static int getInt(String mess) {
    int val;
    while (true) { // loop until we get a valid int
        String s = JOptionPane.showInputDialog(null, mess);
        try {
            val = Integer.parseInt(s);
            break;  // exit loop with valid int >>>>>>>>>>>>>>>>>>>>>>
        }catch (NumberFormatException nx) {
            JOptionPane.showMessageDialog(null, "Enter valid integer");
        }
    }
    return val;
}//end getInt

Non-decimal Integers

Convert integers with some base (radix) other than 10
by using these two methods. Typically these will be hexadecimal (base 16)
or binary (base 2) numbers.

typeExample statement
int
i = Integer.parseInt(s, radix);
long
l = Long.parseLong(s, radix);

For example, to convert a string containing the hexadecimal number “F7” to an integer,
call

i = Integer.parseInt("F7", 16)

See also