整数と浮動小数点数を書式化して表示

明解C言語 入門編 > 2. 演算と型 >

整数と浮動小数点数を書式化して表示

Java
class Lesson015 {
    public static void main(String[] args) {
        System.out.printf("[%d]\n",     123);
//      System.out.printf("[%.4d]\n",   123);
        System.out.printf("[%4d]\n",    123);
        System.out.printf("[%04d]\n",   123);
        System.out.printf("[%-4d]\n\n", 123);

        System.out.printf("[%d]\n",     12345);
//      System.out.printf("[%.3d]\n",   12345);
        System.out.printf("[%3d]\n",    12345);
        System.out.printf("[%03d]\n",   12345);
        System.out.printf("[%-3d]\n\n", 12345);

        System.out.printf("[%f]\n",         123.45);
        System.out.printf("[%.1f]\n",       123.45);
        System.out.printf("[%4.1f]\n",      123.45);
        System.out.printf("[%10.10f]\n\n",  123.45);
    }
}

実行結果

L:\>java Lesson015
[123]
[ 123]
[0123]
[123 ]

[12345]
[12345]
[12345]
[12345]

[123.450000]
[123.5]
[123.5]
[123.4500000000]