Concatenating with an empty String
Easiest way to convert float to a string is to concatenate float with an empty string. That will give you a string value, conversion is handled for you.
public class FloatToString {
public static void main(String[] args) {
float num = 7.345f;
String value = "" + num;
System.out.println("Value is " + value);
}
}
Output
Value is 7.345
Using valueOf() method of String class
String class has valueOf() method which is overloaded and those variants take int, float, double, long data types as parameters. Using valueOf(float f) method will return string representation of the float argument.
public class FloatToString {
public static void main(String[] args) {
float num = -97.345f;
String value = String.valueOf(num);
System.out.println("Value is " + value);
}
}
Output
Value is -97.345
toString() method of the wrapper classes
Each of the Number subclass (Integer, Float, Double etc.) includes a class method, toString(), that will convert its primitive type to a string. Thus, using Float.toString(float f) returns a String object representing the specified float value.
public class FloatToString {
public static void main(String[] args) {
float num = 78.34576865959f;
String value = Float.toString(num);
System.out.println("Value is " + value);
}
}
Output
Value is 78.34577
Here note that vale has been rounded off. That is one thing to be considered while converting float values that those are not precise.
That's all for this topic Converting float to string - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -