Signup/Sign In

How to Convert Float to String in Java

In this post, we are going to convert float type to string in Java. Float is a datatype that holds floating-point values whereas String is a sequence of characters and a class in Java.

To convert Float to String there are several ways like the valueOf() method of String class or toString() method of Float class or a simple string literal that converts an expression to string.

The valueOf() method belongs to String that returns a string of the specified value and The toString() method of Float class returns a string of the floating-point value.

Here, we are going to see all these conversions with the help of several examples.

Time for an Example:

Let's take an example to convert float to a string. Here, we are using the valueOf() method of the String class to get a string from a float value.

public class Main {
	public static void main(String[] args){
		Float val = 12.50f;
		System.out.println(val);
		// Float to String
		String str = String.valueOf(val);
		System.out.println(str);
		System.out.println(str.getClass().getName());
	}
}


12.5
12.5
java.lang.String

Example: Convert using toString() Method

Let's create another example to get a string from float type. Here, we are using the toString() method of Float class that returns a string of the specified value.

public class Main {
	public static void main(String[] args){
		Float val = 12.50f;
		System.out.println(val);
		// Float to String
		String str = Float.toString(val);
		System.out.println(str);
		System.out.println(str.getClass().getName());
	}
}


12.5
12.5
java.lang.String

Example: Convert using String literals

There is another way to convert float to string. Here, we are using a string literal and append that using plus to the floating-point. This is an implicit conversion of Java that returns a string if we concatenate any type to the string literal.

public class Main {
	public static void main(String[] args){
		Float val = 12.50f;
		System.out.println(val);
		// Float to String
		String str = ""+val;
		System.out.println(str);
		System.out.println(str.getClass().getName());
	}
}


12.5
12.5
java.lang.String



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.