Java - Convert float to string
If you have come to this page chances are that you need to convert a float to a String in Java. This is relatively easy. There is more than one way to do this. We are going to cover these but it is up to you which method you prefer.
Quick solution: Here are four different methods to convert a float to a string:
String s = "" + f;
String s = String.valueOf(f);
String s = Float.toString(f);
String s = String.format("%d",f);
Keep reading for more details and slightly better examples.
String Concatenation
This first method is my favorite. You can simply concatenate a float with a string literal and assign the result to a String. We print out the result and the type of the variable.
float f = 123.45f;
String s = "" + f;
System.out.println(s);
System.out.println(s.getClass().getName());
String.valueOf()
This method uses the valueOf() method of the String class. It will give us the String value of a float that we pass to it. This can then be returned to a String variable.
float f = 123.45f;
String s = String.valueOf(f);
System.out.println(s);
System.out.println(s.getClass().getName());
Float.toString()
The Float class itself has a toString() method that will return a String representation of whatever float you pass to it. It works pretty much as you would expect. You can assign the value to a String variable.
float f = 123.45f;
String s = Float.toString(f);
System.out.println(s);
System.out.println(s.getClass().getName());
String.format()
This method also works fine but it isn’t my favorite. To me it just feels a little bit messy as you probably won’t normally get any benefit out of having to specify the format. The String class has a format() method that allows you to construct a string anyway you like. One benefit of this method is that it allows you to control things like leading zeros ( see the next section below ).
float f = 123.45f;
String s1 = String.format("%01.2f",f);
String s2 = String.format("%01.4f",f);
System.out.println(s1); // 123.45
System.out.println(s2); // 123.4500
System.out.println(s1.getClass().getName());
System.out.println(s2.getClass().getName());
Java Convert float to String with Leading Zeros
Converting an int to a String with leading zeros is easy with Java. For this we can use the format() method of the String class. We specify “%08d” for the format. This means that the number will be padded with 0 and it will be padded up to 8 spaces.
float f = 123.45f;
String s1 = String.format("%08.2f", f);
String s2 = String.format("%08.5f", f);
String s3 = String.format("%015.2f", f);
String s4 = String.format("%015.3f", f);
System.out.println(s1); // 00123.45
System.out.println(s2); // 123.45000
System.out.println(s3); // 000000000123.45
System.out.println(s4); // 00000000123.450