I tried using String.format
to format some floats.
If I do this:
public class TestClass {
public static void main(String[] args) {
System.out.println(String.format("%5.2f %5.2f", 2.35792f, 8.9479f));
}
}
Then it seems to work and prints out 2.36 8.95
.
However, if I extract this to a method:
public class TestClass {
public static void main(String[] args) {
System.out.println(formatFloats(2.35792f, 8.9479f));
}
private static String formatFloats(float...fs) {
StringBuilder formatStr = new StringBuilder();
for (float v: fs) {
formatStr.append("%5.2f ");
}
return String.format(formatStr.toString().trim(), fs);
}
}
then it raises an exception:
Exception in thread "main" java.util.IllegalFormatConversionException: f != [F
at java.base/java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4426)
at java.base/java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2951)
at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:2898)
at java.base/java.util.Formatter.format(Formatter.java:2673)
at java.base/java.util.Formatter.format(Formatter.java:2609)
at java.base/java.lang.String.format(String.java:3292)
at demo.vec3.TestClass.formatFloats(TestClass.java:12)
at demo.vec3.TestClass.main(TestClass.java:4)
I tried to print formatStr.toString().trim()
, but it does output %5.2f %5.2f
.
The error message is cryptic, and I don't understand what it means at all. I believe it has something to do with how I am using float...fs
.
(I am using Eclipse IDE to write and run my application.)
Remark: It turns out that if I change my function code slightly to this:
private static String formatFloats(Object...fs) {
StringBuilder formatStr = new StringBuilder();
for (Object v: fs) {
formatStr.append("%5.2f ");
}
return String.format(formatStr.toString().trim(), fs);
}
then it works, outputting 2.36 8.95
again.
CodePudding user response:
You're correct. When you pass in a float[]
, Java thinks you are trying to print one argument, a float[]
, rather than all the individual float elements of the array. Only an Object[]
is compatible with the varargs used by String.format
, allowing each individual float to be interpreted as a separate format
argument.
Note that Float[]
will also work, since Float[]
can be upcast to Object[]
, but float[]
cannot.
CodePudding user response:
You can use your first rendition of the formatFloats()
method, you just need to actually do the formatting within the StringBuilder append, for example:
private static String formatFloats(float... fs) {
StringBuilder formatStr = new StringBuilder("");
for (float v: fs) {
formatStr.append(String.format("%-6.2f ", v));
}
return formatStr.toString();
}