Tuesday, November 3, 2015

A brief in Java string format

When to format a Java String using System.out.printf or System.out.format, The syntax for the format is :

%[arg_index$][flags][width][.precision]<conversion_char>

Here are more explanation:
  • arg_index    An integer with suffix '$'. begin with 1, not 0. The position of the args.
  • flags 
    - Left-align, default is right-aligned
    + Include +/-before number
    0 Pad with zeros before number
    , User comma to separate number
    ( Enclose negative numbers in parentheses. '-' will not display
  • width  The width of the printed String, very useful to get table like output
  • precision  For float/double, specify the digits after "."
  • Conversion_char
    b boolean
    c char
    d integer
    f float/double
    s string

Below is a simple example for demostration

    System.out.printf("<%-3s><%6s><%10s><%10s>\n","Id","Gender","Name","Balance");
System.out.printf("<%3$03d><%2$6s><%1$10s><%4$+10.2f>\n", "Tom","M",1,688.972); // arg_indx
System.out.printf("<%03d><%6s><%10s><%+10.2f>\n", 2,"M","Jerry",-12.345);
System.out.printf("<%03d><%6s><%10s><%(10.2f>\n", 3,"F","Rose",-12.345);

The "<"  and ">" are added to make the border visible. The outputs are:

<Id ><Gender><      Name><   Balance>
<001>< M>< Tom>< +688.97>
<002>< M>< Jerry>< -12.35>
<003>< F>< Rose>< (12.35)>

0 comments:

Post a Comment

Powered by Blogger.

About The Author

My Photo
Has been a senior software developer, project manager for 10+ years. Dedicate himself to Alcatel-Lucent and China Telecom for delivering software solutions.

Pages

Unordered List