This example shows how to convert string to float in Java using the parseFloat method of the Float wrapper class including the NumberFormatException.
How to convert String to float in Java?
To convert a string to float primitive value, use the parseFloat
method of the Float wrapper class.
1 |
public static float parseFloat(String strFloatNumber) |
This method returns a float primitive value by parsing the input string value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.javacodeexamples.basic; public class StringToFloatExample { public static void main(String[] args){ String strNumber = "3.243"; /* * Use Float.parseFloat() method to * convert String to float primitive value */ float f = Float.parseFloat(strNumber); System.out.println("String to float: " + f); } } |
Output
1 |
String to float: 3.243 |
Important Note:
If the floating-point number cannot be parsed from the input string value, the parseFloat
method throws a NumberFormatException exception.
Also, if the string is null, the parseFloat
method throws a NullPointerException exception.
1 2 |
String strNumber = "3.abc4"; float f = Float.parseFloat(strNumber); |
Output
1 2 3 4 |
Exception in thread "main" java.lang.NumberFormatException: For input string: "3.abc4" at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source) at java.lang.Float.parseFloat(Unknown Source) at com.javacodeexamples.basic.StringToFloatExample.main(StringToFloatExample.java:19) |
Here are some of the example string values and their possible outputs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//decimal(.) sign is allowed, output 783.43 System.out.println( Float.parseFloat("783.43") ); //Plus sign is allowed as a first char, output 234.23 System.out.println( Float.parseFloat("+234.23") ); //Minus sign is allowed as first char, output -234.23 System.out.println( Float.parseFloat("-234.23") ); //NumberFormatException System.out.println( Float.parseFloat("123.45.67") ); //NumberFormatException System.out.println( Float.parseFloat("123.abc") ); /* * even empty string is not allowed, * NumberFormatException is thrown for input String: "" */ System.out.println( Float.parseFloat("") ); |
Please note that the “+” (plus sign) or “-” (minus sign) is allowed as a first character of the string to denote positive and negative value numbers respectively.
This example is a part of the Java Basic Examples and Java Type conversion Tutorial.
Please let me know your views in the comments section below.