java 使用DecimalFormat進行數字的格式化實例詳解
簡單實例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
//獲取DecimalFormat的方法DecimalFormat.getInstance(); public static void test1(DecimalFormat df) { //默認顯示3位小數 double d = 1.5555555 ; System.out.println(df.format(d)); //1.556 //設置小數點后最大位數為5 df.setMaximumFractionDigits( 5 ); df.setMinimumIntegerDigits( 15 ); System.out.println(df.format(d)); //1.55556 df.setMaximumFractionDigits( 2 ); System.out.println(df.format(d)); //1.56 //設置小數點后最小位數,不夠的時候補0 df.setMinimumFractionDigits( 10 ); System.out.println(df.format(d)); //1.5555555500 //設置整數部分最小長度為3,不夠的時候補0 df.setMinimumIntegerDigits( 3 ); System.out.println(df.format(d)); //設置整數部分的最大值為2,當超過的時候會從個位數開始取相應的位數 df.setMaximumIntegerDigits( 2 ); System.out.println(df.format(d)); } public static void test2(DecimalFormat df) { int number = 155566 ; //默認整數部分三個一組, System.out.println(number); //輸出格式155,566 //設置每四個一組 df.setGroupingSize( 4 ); System.out.println(df.format(number)); //輸出格式為15,5566 DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(); //設置小數點分隔符 dfs.setDecimalSeparator( ';' ); //設置分組分隔符 dfs.setGroupingSeparator( 'a' ); df.setDecimalFormatSymbols(dfs); System.out.println(df.format(number)); //15a5566 System.out.println(df.format( 11.22 )); //11;22 //取消分組 df.setGroupingUsed( false ); System.out.println(df.format(number)); } public static void test3(DecimalFormat df) { double a = 1.220 ; double b = 11.22 ; double c = 0.22 ; //占位符可以使用0和#兩種,當使用0的時候會嚴格按照樣式來進行匹配,不夠的時候會補0,而使用#時會將前后的0進行忽略 //按百分比進行輸出 // df.applyPattern("00.00%"); df.applyPattern( "##.##%" ); System.out.println(df.format(a)); //122% System.out.println(df.format(b)); //1122% System.out.println(df.format(c)); //22% double d = 1.22222222 ; //按固定格式進行輸出 df.applyPattern( "00.000" ); System.out.println(df.format(d)); //01.222 df.applyPattern( "##.###" ); System.out.println(df.format(d)); //1.222 } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/elim168/article/details/40586319