Friday, August 5, 2011

Java printf Percent (%) Sign

To put the percent sign '%' in as a literal,

System.out.printf("\nTested %d reports.  Found differences in %d reports.  %2.2f%% passed.  %2.2f%% failed.\n", 7, 1, ((float)(7-1)/7)*100, ((float)1/7)*100);
%[argument_index$][flags][width][.precision]conversion
 
The optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc. 
The optional flags is a set of characters that modify the output format. The set of valid flags depends on the conversion. 
The optional width is a non-negative decimal integer indicating the minimum number of characters to be written to the output. 
The optional precision is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion. 
The required conversion is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.

1 comment:

  1. Hello I had a question regarding the $ sign in the printf method.
    So I was building a print calendar method and was wondering what this means
    printf("%1$2d",date);
    where date is a number between 1 and number of days in the month.
    How is that printf interpretted.

    Thank you!

    ReplyDelete