LAST UPDATED: SEPTEMBER 1, 2020
Java Float parseFloat() Method
Java parseFloat()
method is the part of the Float
class of the java.lang
package. This method is used to parse the string value to its equivalent float value. This method returns the same value as returned by the Float class's valueOf()
method.
Syntax:
public static float parseFloat(String s) throws NumberFormatException
Parameters:
The parameter passed is the string value whose equivalent float value is to be returned.
Returns:
Returns the equivalent float value corresponding to the string value passed as a parameter.
Exception:
NullPointerException
- if the passed string is null
NumberFormatException
- if the passed string does not contain a parsable float
.
Example 1:
Here, two strings are passed and are returned as their respective float value.
import java.lang.Float;
public class StudyTonight
{
public static void main(String[] args)
{
String s1 = "23.685";
String s2 = "-23.056";
//converts the passed string into its corresponding float value
float n1 = Float.parseFloat(s1);
//converts the passed string into its corresponding float value
float n2 = Float.parseFloat(s2);
System.out.println("Equivalent Float value is : " + n1);
System.out.println("Equivalent Float value is : " + n2);
}
}
Equivalent Float value is : 23.685
Equivalent Float value is : -23.056
Example 2:
Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.
import java.lang.Float;
import java.util.Scanner;
public class StudyTonight
{
public static void main(String[] args)
{
try
{
System.out.println("Enter Value");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
Float n = Float.parseFloat(s); //converts the passed string as float value
System.out.println("Equivalent Float value is : " + n);
}
catch(Exception e)
{
System.out.println("Invalid Input!!");
}
}
}
Enter Value
845
Equivalent Float value is : 845.0
************************************
Enter Value
-523
Equivalent Float value is : -523.0
*************************************
Enter Value
mohit
Invalid Input!!
Live Example:
Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.