Java Program to Convert Float to String

This article shows how to write a Java Program to Convert Float to String. In Java, we can convert Float to string using the traditional String.valueOf(f) function, Float.toString(), or String.format() function.

In this Java example, we declared two floating point values. Next, we used the String.valueOf() function to convert the float values to string. Then, we printed those converted string data as an output.

public class floatToString {

	public static void main(String[] args) {
		
		float f1 = 102.53F;
		float f2 = 22.96F;
		
		String s1 = String.valueOf(f1);
		String s2 = String.valueOf(f2);
		
		System.out.println("String.valueOf(f1) result = " + s1);
		System.out.println("String.valueOf(f2) result = " + s2);
	}
}
String.valueOf(f1) result = 102.53
String.valueOf(f2) result = 22.96

Java Convert Float to String

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

public class floatToString {

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

This time we are using the String.format() function with required format specifier, i.e., %f.

public class floatToString {

	public static void main(String[] args) {
		
		float f1 = 1459.2223F;
		float f2 = 90.68764F;
		
		String s1 = String.format("%.3f", f1);
		String s2 = String.format("%.2f", f2);
		
		System.out.println("F1 Formatted to Str = " + s1);
		System.out.println("F2 Formatted to Str = " + s2);
	}
}
F1 Formatted to Str = 1452.222
F2 Formatted to Str = 90.69

Java Program to Convert Float to String example 4

This Java Float to string program allows user to enter the value. Next, we used all the three functions valueOf(f), format(), and toString(), on that user given value.

import java.util.Scanner;

public class floatToString {

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

		System.out.println("\n Please Enter any Float Value :  ");
		f1 = sc.nextFloat();
		
		String str1 = String.valueOf(f1);
		String str2 = Float.toString(f1);
		String str3 = String.format("%.3f", f1);
		
		System.out.println("Float f1 Converted to String Value = " + str1);
		
		System.out.println("Float f1 Converted to String Value = " + str2);
		
		System.out.println("Float f1 Converted to String Value = " + str3);
	}
}
Java Program to Convert Float to String 4