RFC: 6178739 - Formatter - Zero padding flag with zero width

Brian Burkhalter brian.burkhalter at oracle.com
Mon Jun 24 19:56:17 UTC 2013


This issue

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6178739

exposes what could be either a minor specification or implementation flaw depending on one's interpretation. The test case is

public class TestFormat {
    public static void main(String argv[]) {
        System.out.printf("%1.4f\n", 56789.456789);
        System.out.printf("%0.4f\n", 56789.456789); // java.util.MissingFormatWidthException
    }
}

The format specification applicable to the "%f" conversion is

%[argument_index$][flag][width][.precision]conversion

The problem comes in because, according to the specification,

1) zero (0) is a legal flag which indicates that the output should be zero-padded, and
2) width is a non-negative value indicating the minimum number of characters to be printed.

The outcome is that the format string which provokes the exception above could be seen to be ambiguous: it could be interpreted to mean either that the output is zero-padded or that the minimum number of characters to print is zero. If one however uses the format string "%00.4f\n" to indicate zero padding and zero width it provokes a java.util.DuplicateFormatFlagsException.

By way of comparison, this C code

    printf("%1.4f\n", 56789.456789F);
    printf("%0.4f\n", 56789.456789F);

prints this output

56789.4570
56789.4570

and providing the format string "%00.4f" is a compilation error.

This result appears to assume a default width of zero for the zero-padded case which seems to be reasonable behavior, but it is precluded for the Formatter by the javadoc for the zero-padding flag:

"Requires the output to be padded with leading zeros to the minimum field width following any sign or radix indicator except when converting NaN or infinity. If the width is not provided, then a MissingFormatWidthException will be thrown."

Comments?

Brian


More information about the core-libs-dev mailing list