定評のある Java 解説書 ``Core Java'' の著者である、 Cay Horstmann のホームページ http://www.horstmann.com/ には、 ``The March of Progress'' として、かつて次のようなことが載っていた。
C
printf("%10.2f", x);
C++
cout << setw(10) << setprecision(2) << showpoint << x;
Java
java.text.NumberFormat formatter
= java.text.NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String s = formatter.format(x);
for (int i = s.length(); i < 10; i++)
System.out.print(' ');
System.out.print(s);
|
痛烈な皮肉だが (分かるかな?)、 この著者は解決策として、Format というクラスを 提示している7。 それを用いると、次の TestFormat.java のようなコーディングができる。
| TestFormat.java |
1 /*
2 * TestFormat.java -- C 言語の printf() 風の書式指定
3 *
4 * Format.java の入手
5 * Cay Horstmann (http://www.horstmann.com/) 作
6 * http://www.horstmann.com/corejava/Format.java
7 *
8 * コンパイルの準備
9 * mkdir corejave
10 * cp どこか/Format.java corejava
11 * cd corejava
12 * javac Format.java
13 * cd ..
14 */
15
16 import corejava.*;
17
18 public class TestFormat {
19 public static void main(String args[]) {
20 // Format.print() メソッド --- ただし一つの書式指定しか使えない
21 Format.print(System.out, "%12.8f\n", Math.PI);
22 // 吉田祐一郎はこういう使い方を勧めていた
23 Format fmt = new Format("%12.8f");
24 System.out.println("PI=" + fmt.form(Math.PI) +
25 ", e=" + fmt.form(Math.exp(1)));
26 }
27 }
|
| TestFormat.class の実行結果 |
1 yurichan% java TestFormat 2 3.14159265 3 PI= 3.14159265, e= 2.71828183 4 yurichan% |
確かにこれなら許せるというか、心安らぐプログラミングが出来そうである。
実は、現在では少し変わっていて、次のようになっている。
| The March of Progress |
The March of Progress
1980: C
printf("%10.2f", x);
1988: C++
cout << setw(10) << setprecision(2) << showpoint << x;
1996: Java
java.text.NumberFormat formatter =
java.text.NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2); String s =
formatter.format(x); for (int i = s.length(); i < 10; i++)
System.out.print(' '); System.out.print(s);
2004: Java
System.out.printf("%10.2f", x);
|
結局、Java にも printf() が入ったと言うことです (ちゃんちゃん)。