How to convert float to String in Java
How to convert float to String in java
There are following methods to convert float to String:
- Convert using Float.toString(float)
- Convert using String.valueOf(float)
Convert using Float.toString(float)
The Float class has a static method that returns a String object representing the specified float parameter. It returns the string representation of the float argument. The minus sign will be preserved if the number is negative. This is the most common method for converting the float value to String. The signature of this method is-
public static String toString(float f)
Where f represents the float value that we want to convert.
This method works similar to the String.valueOf(float) method except that it belongs to the Float class.
Example
In the following example, var is a variable of type float having value -7.22. str is a variable of type String that stores the value of var after conversion. Float is a wrapper class. toString() is a method of String class having var as an argument and returns the String representation of float value. The println statement prints the converted value of var.
public class FloatToStringExample1 { public static void main(String[] args) { float var = -7.22f; //the suffix f denotes the float representation String str = Float.toString(var); //conversion using to String() method System.out.println("After Conversion String is: "+str); } }
Output
After Conversion String is: -7.22
Convert using String.valueOf(float)
It is an overloaded method of String class under the java.lang package. You can pass the float value to this method as an argument. It returns the string representation of it. The signature of this method is-
public static String valueOf(float f)
Where f represents the float value that we want to convert.
Example
In the following example, val is a variable of type float having value 21.20. str is a variable of type String that stores the value of val after conversion. String is a class. valueOf() is a method of String class having val as an argument and returns the String representation of float value. The println statement prints the converted value of val.
public class FloatToStringExample2 { public static void main(String[] args) { float val= 21.20f; //the suffix f denotes the float representation String str = String.valueOf(val); //conversion using valueOf() method System.out.println("After conversion String is: "+str); }
Output
After conversion String is: 21.2