Java 8 has methods for converting string to numbers: integer, float, double:

  • Integer.parseInt() - to convert a String to int.
  • Integer.valueOf(numberV) - to convert a String to int.
  • Double.parseDouble() - to convert a String to Double.
  • Double.valueOf(numberDV) - to convert a String to Double.
  • Float.parseFloat() - to convert a String to Float.
  • Float.valueOf(numberFV) - to convert a String to Float.

difference between: parseXxx() and valueOf

parseXxx() returns the primitive type
valueOf() returns a wrapper object reference of the type.

java convert string to double

Example how to convert string to double:

String numberD = "100.1";
Double resultD = Double.parseDouble(numberD);
System.out.println(resultD);

String numberDV = "100.1";
Double resultDV = Double.valueOf(numberDV);
System.out.println(resultDV);

result

100.1
100.1

java convert string to int

Converting string to integer can be done by:

String number = "100";
int result = Integer.parseInt(number);
System.out.println(result);

String numberV = "100";
Integer resultV = Integer.valueOf(numberV);
System.out.println(resultV);

result

100
100

java convert string to float

Converting string to float:

String numberF = "100.1";
Float resultF = Float.valueOf(numberF);
System.out.println(resultF);

String numberFV = "100.1";
Float resultFV = Float.valueOf(numberFV);
System.out.println(resultFV);

result

100.1
100.1

error converting to number

In case of wrong types the code will produce error. This code below is giving an error like:

String numberE = "100.1";
int resultE = Integer.parseInt(numberD);
System.out.println(resultE);

error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "100.1"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at String.StringTest.main(StringTest.java:33)