How to convert a String to float in Java

We can convert a String to a primitive float using the Float.parseFloat method or to a wrapped Float class using the Float.valueOf. When both methods receive an invalid number as argument, a java.lang.NumberFormatException will be thrown.

Convert a String to float using Float.parseFloat

The Floate.parseFloat method is used to convert a String to primitive float.

String number = "1234.56";
float convertedNumber = Float.parseFloat(number);
System.out.println("Convert String to float: " + convertedNumber);

String negativeNumber = "-1234.56";
float convertedNegativeNumber = Float.parseFloat(negativeNumber);
System.out.println("Convert negative String to float: " + convertedNegativeNumber);

The previous will generate the following output.

Convert String to float: 1234.56
Convert negative String to float: -1234.56

Convert a String to Float using Float.valueOf

The Float.valueOf method is used to convert a String to a wrappedFloat.

String number = "1234.56";
Float convertedNumber = Float.valueOf(number);
System.out.println("Convert String to Float: " + convertedNumber);

String negativeNumber = "-1234.56";
Float convertedNegativeNumber = Float.valueOf(negativeNumber);
System.out.println("Convert negative String to Float: " + convertedNegativeNumber);

The previous will generate the following output.

Convert String to float: 1234.56
Convert negative String to float: -1234.56

throws java.lang.NumberFormatException

If the String passed in is not a valid Float, an java.lang.NumberFormatException is thrown. In this example "-abc" is not a valid number for type Float.

String invalidNumber = "-abc";
float invalidConvertedNumber = Float.parseFloat(invalidNumber);

The java.lang.NumberFormatException thrown.

Exception in thread "main" Convert negative String to float: -1234.56
java.lang.NumberFormatException: For input string: "-abc"
	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
	at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
	at java.lang.Float.parseFloat(Float.java:451)
	at com.memorynotfound.ParseFloatExample.main(ParseFloatExample.java:16)

References

Download

You may also like...