個人覺得NumberFormat還蠻好用的,有時後處理一些數據的輸出時可以用他來稍微加工一下
下面是NumberFormat的一些範例
更詳細的話參考Java API會比較完整喔
複製內容到剪貼板
代碼:
NumberFormat formatter = new DecimalFormat("000000");
String s = formatter.format(-1234.567); // -001235
formatter = new DecimalFormat("##");
s = formatter.format(-1234.567); // -1235
s = formatter.format(0); // 0
formatter = new DecimalFormat("##00");
s = formatter.format(0); // 00
formatter = new DecimalFormat(".00");
s = formatter.format(-.567); // -.57
formatter = new DecimalFormat("0.00");
s = formatter.format(-.567); // -0.57
formatter = new DecimalFormat("#.#");
s = formatter.format(-1234.567); // -1234.6
formatter = new DecimalFormat("#.######");
s = formatter.format(-1234.567); // -1234.567
formatter = new DecimalFormat(".######");
s = formatter.format(-1234.567); // -1234.567
formatter = new DecimalFormat("#.000000");
s = formatter.format(-1234.567); // -1234.567000
formatter = new DecimalFormat("#,###,###");
s = formatter.format(-1234.567); // -1,235
s = formatter.format(-1234567.890); // -1,234,568
formatter = new DecimalFormat("#;(#)");
s = formatter.format(-1234.567); // (1235)
formatter = new DecimalFormat("'#'#");
s = formatter.format(-1234.567); // -#1235
formatter = new DecimalFormat("'abc'#");
s = formatter.format(-1234.567); // -abc1235