Tuesday, 20 September 2016

Converting float to string - Java Program

In the post converting String to float we have already seen ways to do that conversion. This post is about doing just the reverse; convert float values to string.

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

  1. Converting int to string - Java Program
  2. Converting string to bytearray - Java Program
  3. Check whether a given String/Number is a palindrome or not
  4. How to find all the permutations of the given String
  5. Java String interview questions

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment