Write Java program to Convert String to Float
This is a Java program that demonstrates how to convert a string to a float using two different methods: Float.valueOf().floatValue() and Float.parseFloat().
- In this program, a Scanner object named input is created to read input from the user. The program prompts the user to enter a float value and reads the input as a string using the Scanner.next() method. The string is then printed using the System.out.println() method.
- Next, a float variable float_val is initialized to 0.
- The program then uses the Float.valueOf().floatValue() method to convert the string to a float. This method first calls the Float.valueOf() method, which returns a Float object that represents the value of the string.
- The Float.floatValue() method is then called on the returned object to get the float value. The float value is then assigned to the float_val variable, and the value is printed using the System.out.println() method.
- Finally, the program uses the Float.parseFloat() method to convert the string to a float. This method directly parses the string and returns the float value. The float value is then assigned to the float_val variable, and the value is printed using the System.out.println() method.
Source Code
import java.util.Scanner;
public class StringToFloat
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
String str;
System.out.print("Enter the Float Value : ");
str = input.next();
System.out.println("String Value : " + str);
float float_val = 0;
//floatValue() Method 1
float_val = Float.valueOf(str).floatValue();
System.out.println("Float Value Using floatValue() Method : " + float_val);
//parseFloat() Method 2
float_val = Float.parseFloat(str);
System.out.println("Float Value Using parseFloat() Method : " + float_val);
}
}
Output
Enter the Float Value : 84.45371
String Value : 84.45371
Float Value Using floatValue() Method : 84.45371
Float Value Using parseFloat() Method : 84.45371