Menu

How to Convert String to float in Java?

How to convert Java String to float

In Java, a String can be converted into a float value by using the Float.parseFloat() method and by using the Float.valueOf() method. Let's see the conversion.

1. By Using Float.parseFloat() Method

The parseFloat() method is a part of the Float class. It is a static method and is used to convert the string into a float value.

Example 1:

Here, a string value is converted into the float values by using the parseFloat() method.

public class StudyTonight
{  
    public static void main(String args[])
    {  
        String s = "454.86"; //String Decleration 
        float i = Float.parseFloat(s);  // Float.parseFloat() converts the string into float
        System.out.println(i);  
    }
}

Output:

454.86

2. By Using Float.valueOf() Method

The valueOf() method is a part of Float class. This method is used to convert a String into a Float Object.

Example 2:

Here, a String value is converted into a float value by using the valueOf() method.

public class Main
{  
    public static void main(String args[])
    {  
        try
        {
            String s1 = "500.778"; //String  
            float i1 = Float.valueOf(s1);  // Float.valueOf() method converts a String into float
            System.out.println(i1);  
            String s2 = "mohit"; //NumberFormatException
            float i2 = Float.valueOf(s2);
            System.out.println(i2);
        }
        catch(Exception e)
        {
            System.out.println("Invalid input");
        }
    }
}

Output:

500.778 Invalid input

3. By using floatValue() Method

Example 3:

Here, a string is converted into a float value by using the floatValue() method that considering the extra spaces that can occur in the string.

public class StudyTonight
{
    public static void main (String[] args)
    {
        String s = "34.00";
        try
        {
            float f = Float.valueOf(s.trim()).floatValue();
            System.out.println("float value is = " + f);
        }
        catch (NumberFormatException nfe)
        {
            System.out.println("NumberFormatException: " + nfe.getMessage());
        }
    }
}

Output:

float value is = 34.0