April 12, 2024

How to Convert float to String in Java

This post shows how you can convert float to String in Java.

1. Converting float to String using Float.toString() method

Wrapper class Float in Java has toString() method that returns a string representation of the passed float argument.

public class FloatToString {
  public static void main(String[] args) {
    float val = 28.92f;
    String strVal = Float.toString(val);
    System.out.println("Converted String value = " + strVal);
  }
}
Output
Converted String value = 28.92

2. Convert using String.valueOf() method

String.valueOf(float f)- Returns the string representation of the float argument.

public class FloatToString {
  public static void main(String[] args) {
    float val = 28.92f;
    String strVal = String.valueOf(val);
    System.out.println("Converted String value = " + strVal);
  }
}
Output
Converted String value = 28.92

3. Converting using String concatenation

You can concatenate the float value with an empty string ("") that will return the result as a String. That's one way to convert float to String

public class FloatToString {
  public static void main(String[] args) {
    float val = 108.256f;
    String strVal = val + "";
    System.out.println("Converted String value = " + strVal);
  }
}
Output
Converted String value = 108.256

4. Converting using append method of StringBuilder or StringBuffer class

Both StringBuilder and StringBuffer classes have append() method where you can pass float as an argument. The append() method will append the string representation of the float argument to the sequence.

public class FloatToString {
  public static void main(String[] args) {
    float val = -49.12f;
    StringBuilder sb = new StringBuilder();
    sb.append(val);
    System.out.println("Converted String value = " + sb.toString());
  }
}
Output
Converted String value = -49.12

That's all for the topic How to Convert float to String in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment