Java Data Type How to - Format with the space format specifiers to leave space for negative value








Question

We would like to know how to format with the space format specifiers to leave space for negative value.

Answer

import java.util.Formatter;
/*from w  w w. j a va  2s  .com*/
public class MainClass {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();

    fmt.format("% d", -100);
    System.out.println(fmt);

    fmt = new Formatter();
    fmt.format("% d", 100);
    System.out.println(fmt);

    fmt = new Formatter();
    fmt.format("% d", -200);
    System.out.println(fmt);

    fmt = new Formatter();
    fmt.format("% d", 200);
    System.out.println(fmt);
  }
}

The code above generates the following result.