In the post converting String to float we have already seen ways to convert String to float in Java. This post is about doing just the reverse; convert float to string in Java.
Concatenating with an empty String
Easiest way to convert float to a string in Java 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); System.out.println("Type of value is " + value.getClass().getSimpleName()); } }
Output
Value is 7.345 Type of value is String
Converting float to String in Java using valueOf() method
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 you can convert float to String in Java by passing float as an argument to the method and method returns 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
Using toString() method of the Float wrapper class
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)
method you can convert float to String in Java, method returns a String object representing the passed 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 Convert float to String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment