Convert float to String in Java

Tags: String float Convert DecimalFormat

In this Java core tutorial, we learn how to convert float value into String value in Java via different solutions.

Using String.valueOf() method to convert float value to String

ConvertFloatToStringExample1.java

public class ConvertFloatToStringExample1 {
    public static void main(String[] args) {
        float value1 = 12.0203F;
        String value2 = String.valueOf(value1);

        System.out.println("float value: " + value1);
        System.out.println("String value: " + value2);
    }
}
The output is:
float value: 12.0203
String value: 12.0203

Convert float value to String value using Float.toString() static method

ConvertFloatToStringExample2.java

public class ConvertFloatToStringExample2 {
    public static void main(String[] args) {
        float value1 = 12.1213F;
        String value2 = Float.toString(value1);

        System.out.println("float value: " + value1);
        System.out.println("String value: " + value2);
    }
}
The output is:
float value: 12.1213
String value: 12.1213

Using Float.toString() to get String value of a Float object

ConvertFloatToStringExample3.java

public class ConvertFloatToStringExample3 {
    public static void main(String[] args) {
        Float value1 = 79.9897F;
        String value2 = value1.toString();

        System.out.println("float value: " + value1);
        System.out.println("String value: " + value2);
    }
}
The output is:
float value: 79.9897
String value: 79.9897

Format a float value as String using String.format() method

ConvertFloatToStringExample4.java

public class ConvertFloatToStringExample4 {
    public static void main(String[] args) {
        float value1 = 56.12345F;
        String value2 = String.format("%.5f", value1);

        System.out.println("float value: " + value1);
        System.out.println("String value: " + value2);
    }
}
The output is:
float value: 56.12345
String value: 56.12345

Format a float value as String using DecimalFormat class

ConvertFloatToStringExample5.java

import java.text.DecimalFormat;

public class ConvertFloatToStringExample5 {
    public static void main(String[] args) {
        double value1 = 99.010203;
        DecimalFormat decimalFormat = new DecimalFormat("#.######");
        String value2 = decimalFormat.format(value1);

        System.out.println("float value: " + value1);
        System.out.println("String value: " + value2);
    }
}
The output is:
float value: 99.010203
String value: 99.010203

Happy Coding 😊