Learn to convert float value to String using Float.toString() and String.valueOf() methods after formatting it to n decimal points. The recommended approach is using the Float.toString() method.
1. Using Float.toString()
The Float.toString() method returns a String representation of the float value passed as the argument. The conversion works well with positive and negative numbers.
float PI = 3.1415927f;
float negativePI = -3.1415927f;
Assertions.assertEquals("3.1415927", Float.toString(PI));
Assertions.assertEquals("-3.1415927", Float.toString(negativePI));
Note that:
- if the argument is NaN, the result is the string “NaN“. It does not throw any exceptions.
- If the argument is infinity, the result is the string “Infinity“.
Assertions.assertEquals("NaN", Float.toString(0.0f / 0.0f));
Assertions.assertEquals("Infinity", Float.toString(Float.POSITIVE_INFINITY));
Assertions.assertEquals("-Infinity", Float.toString(Float.NEGATIVE_INFINITY));
2. Using String.valueOf()
The String.valueOf() method is overloaded and works with many data types. We can use it with the float type as well. It takes a float value as an argument and returns the equivalent string representation.
The String.valueOf() internally invokes the Float.toString() method so the behavior of the method is similar to former.
float PI = 3.1415927f;
float negativePI = -3.1415927f;
Assertions.assertEquals("3.1415927", String.valueOf(PI));
Assertions.assertEquals("-3.1415927", String.valueOf(negativePI));
3. Format Float to N Decimal Points
We need to use NumberFormat.format(float) method to format float value to string in predefined format – such as set decimal places in the formatted string.
For example, we can format float to 2 decimal points as in the given program.
NumberFormat formatter = new DecimalFormat("0.00");
Assertions.assertEquals("3.14", formatter.format(PI));
In this article, we learned to convert or format a float type to String. You may be interested in reading about the correct way to compare two floating-point numbers.
Happy Learning !!