This post will discuss how to parse a string to a double or float or int in Java.

1. Using Double.parseDouble() method

The standard solution to parse a string to get the corresponding double value is using the Double.parseDouble() method.

Download  Run Code

 
The Double.parseDouble() method throws NumberFormatException if the string does not contain a parsable double. To avoid abrupt program termination, enclose your code within a try-catch block.

Download  Run Code

 
Note, you can’t parse strings like 1.1 using the Integer.parseInt() method. To get the integer value, you can cast the resultant double value.

Download  Run Code

2. Using Float.parseFloat() method

Alternatively, you can use the Float.parseFloat() method to parse a string to a float.

Download  Run Code

 
To get the integer value, cast the resultant float value as discussed before.

Download  Run Code

3. Using Integer.parseInt() method

To get the integer value represented by the string in decimal, you can use the Integer.parseInt() method, which parses the string as a signed decimal integer.

Download  Run Code

4. Using Number class

To parse text from the beginning of the given string to produce a number, you may want to use the parse() method of the NumberFormat class. This method might not use the entire string and throws ParseException if the string starts with any unparseable non-numeric character.

The NumberFormat.parse() method returns a Number class instance, which offers intValue(), longValue(), floatValue(), doubleValue(), byteValue(), and shortValue() methods to get the value of the specified number as a corresponding method type.

Download  Run Code

That’s all about parsing a string to a float or int in Java.