Java Program to Convert String to Float

This article shows how to write a Java program to convert string to Float. In Java, we can convert string to Float using the parseFloat() function and the Float.valueOf() function. In this Java example, we declared two string values. Next, we used the Float.parseFloat() function to convert the string values to Float. Remember, if you provide the text input, the parseFloat() function will throw an error.

public class stringToFloat {

	public static void main(String[] args) {
		String s1 = "10.22F";
		String s2 = "33.21F";
	
		float f1 = Float.parseFloat(s1);
		float f2 = Float.parseFloat(s2);
		
		System.out.println("Float.parseFloat(s1) result = " + f1);
		System.out.println("Float.parseFloat(s2) result = " + f2);
	}
}
Float.parseFloat(s1) result = 10.22
Float.parseFloat(s2) result = 33.21

Java String to Float Program

This Java string to Float example is the same as the above. However, we used the Float.valueOf() function to convert string values to Float data type.

public class stringToFloat {

	public static void main(String[] args) {
		String s3 = "222.186F";
		String s4 = "456.897F";
	
		float f3 = Float.valueOf(s3);
		float f4 = Float.valueOf(s4);
		
		System.out.println("Float.valueOf(s3) result = " + f3);
		System.out.println("Float.valueOf(s3) result = " + f4);
	}
}
Float.valueOf(s3) result = 222.186
Float.valueOf(s3) result = 456.897

Java Program to Convert String to Float example 3

This Java string to Float program allows users to enter string value. Next, we used both the Float.parseFloat() function and Float.valueOf() function on that user given string value.

import java.util.Scanner;

public class stringToFloat {
	private static Scanner sc;

	public static void main(String[] args) {
		String str;
	
		sc= new Scanner(System.in);

		System.out.println("\n Please Enter any Float Value :  ");
		str = sc.nextLine();
	
		float f5 = Float.parseFloat(str);
		float f6 = Float.valueOf(str);
		
		System.out.println("Float.parseFloat() - String to Float = " + f5);
		System.out.println("Float.valueOf() - String to Float = " + f6);
	}
}
Java Program to Convert String to Float 3