Wednesday, March 27, 2024

Convert float to String in Java

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

  1. Convert int to String in Java
  2. Convert float to int in Java
  3. Arrange Non-Negative Integers to Form Largest Number - Java Program
  4. How to Convert Date to String in Java
  5. Java String Interview Questions And Answers

You may also like-

  1. Matrix Multiplication Java Program
  2. Reading Delimited File in Java Using Scanner
  3. How to Untar a File in Java
  4. static Block in Java
  5. Is String Thread Safe in Java
  6. Try-With-Resources in Java With Examples
  7. Java ThreadLocal Class With Examples
  8. AtomicLong in Java With Examples

No comments:

Post a Comment