In this guide, we will see how to convert String to float in Java. We will use the parseFloat()
method of Float class for this conversion.
public static float parseFloat(String str)
This method takes string argument and returns a float number represented by the argument str
.
Program to Convert String to float
public class JavaExample{ public static void main(String args[]){ String str = "15.6515"; float floatNum = Float.parseFloat(str); System.out.println("String to float: "+floatNum); } }
Output:
Print float value upto two decimal places only:
In case, you want to display float number upto a certain number of decimal places then you can use the %.nf
format specifier which tells the compiler to display number upto n decimal places only. Here we want to display only two decimal places so we used %.2f
.
public class JavaExample{ public static void main(String args[]){ String str = "15.6515"; float floatNum = Float.parseFloat(str); System.out.print("String to float: "); System.out.printf("%.2f", floatNum); } }
Output:
Program to Convert String with commas to float
Some countries use comma ,
instead of dot .
to separate decimal parts of the number. In such scenario, we can use the valueOf()
method of Float class. This method expects the string to contain dot instead of comma so we need to call replace()
method of String class to replace the comma with dot.
public class JavaExample{ public static void main(String args[]){ String str = "15,6515"; float floatNum = Float.valueOf(str.replace(",", ".").toString()); System.out.println("String to float: "+floatNum); } }
Output:
String to float: 15.6515