To convert String to float in Java you can use one of the following options-
1- Float.parseFloat(String str)– Returns a new float initialized to the value represented by the specified String.
2- Float.valueOf(String s)– Returns a Float object holding the float value represented by the argument string s.
As you can see parseFloat() method returns a float primitive where as valueOf() method returns a Float object.
Java example to convert String to float using Float.parseFloat
public class StringToFloat { public static void main(String[] args) { String str = "56.45f"; try{ float f = Float.parseFloat(str); System.out.println("value - " + f); // can be used in arithmetic operations now System.out.println(f+"/3 = " + f/3); }catch(NumberFormatException exp){ System.out.println("Error in conversion " + exp.getMessage()); throw exp; } } }
Output
value - 56.45 56.45/3 = 18.816668
For float numbers you can use “f” or “F” (even d or D which denotes double) so a String like this – “56.45f” won’t result in NumberFormatException while converting. But having any other alphabet like “56.45c” will throw exception.
Java example to convert String to float using Float.valueOf
public class StringToFloat { public static void main(String[] args) { String str = "-55.67456"; try{ Float f = Float.valueOf(str); System.out.println("value- " + f); }catch(NumberFormatException exp){ System.out.println("Error in conversion " + exp.getMessage()); throw exp; } } }
Output
value- -55.67456
NumberFormatException
While converting string to float in Java NumberFormatException is thrown if an invalid number string is passed for conversion.
public class StringToFloat { public static void main(String[] args) { String str = "43g"; try{ Float f = Float.valueOf(str); System.out.println("value- " + f); }catch(NumberFormatException exp){ System.out.println("Error in conversion " + exp.getMessage()); throw exp; } } }
Output
Error in conversion For input string: "43g" Exception in thread "main" java.lang.NumberFormatException: For input string: "43g" at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source) at sun.misc.FloatingDecimal.parseFloat(Unknown Source) at java.lang.Float.parseFloat(Unknown Source) at java.lang.Float.valueOf(Unknown Source) at com.knpcode.programs.StringToFloat.main(StringToFloat.java:8)
Related Posts
- How to Convert String to int in Java
- How to Convert String to double in Java
- How to Convert String to Byte Array in Java
- How to Convert float to String in Java
- How to Convert double to String in Java
- Java Program to Convert Numbers to Words
- Java Program to Find Maximum And Minimum Number in a Matrix
- Read Excel File in Java Using Apache POI
That’s all for the topic How to Convert String to float in Java. If something is missing or you have something to share about the topic please write a comment.
You may also like