DecimalFormat的用法

来源:互联网 发布:京东金融网络拓扑 编辑:程序博客网 时间:2024/06/05 01:51
1 DecimalFormat df = new DecimalFormat();
2 double data = 1234.56789;
3 System.out.println("格式化之前的数字: " + data);
4 String style = "0.0";//定义要显示的数字的格式
5 df.applyPattern(style);// 将格式应用于格式化器
6 System.out.println("采用style: " + style + "格式化之后: " + df.format(data));
7 style = "00000.000 kg";//在格式后添加诸如单位等字符
8 df.applyPattern(style);
9 System.out.println("采用style: " + style + "格式化之后: " + df.format(data));
10 // 模式中的"#"表示如果该位存在字符,则显示字符,如果不存在,则不显示。
11 style = "##000.000 kg";
12 df.applyPattern(style);
13 System.out.println("采用style: " + style + "格式化之后: " + df.format(data));
14 // 模式中的"-"表示输出为负数,要放在最前面
15 style = "-000.000";
16 df.applyPattern(style);
17 System.out.println("采用style: " + style + "格式化之后: " + df.format(data));
18 // 模式中的","在数字中添加逗号,方便读数字
19 style = "-0,000.0#";
20 df.applyPattern(style);
21 System.out.println("采用style: " + style + "格式化之后: " + df.format(data));
22 // 模式中的"E"表示输出为指数,"E"之前的字符串是底数的格式,
23 // "E"之后的是字符串是指数的格式
24 style = "0.00E000";
25 df.applyPattern(style);
26 System.out.println("采用style: " + style + "格式化之后: " + df.format(data));
27 // 模式中的"%"表示乘以100并显示为百分数,要放在最后。
28 style = "0.00%";
29 df.applyPattern(style);
30 System.out.println("采用style: " + style + "格式化之后: " + df.format(data));
31 // 模式中的"\u2030"表示乘以1000并显示为千分数,要放在最后。
32 style = "0.00\u2030";
33 //在构造函数中设置数字格式
34 DecimalFormat df1 = new DecimalFormat(style);
35 //df.applyPattern(style);
36 System.out.println("采用style: " + style + "格式化之后: " + df1.format(data));


格式化之前的数字: 1234.56789
采用style: 0.0格式化之后: 1234.6
采用style: 00000.000 kg格式化之后: 01234.568 kg
采用style: ##000.000 kg格式化之后: 1234.568 kg
采用style: -000.000格式化之后: -1234.568
采用style: -0,000.0#格式化之后: -1,234.57
采用style: 0.00E000格式化之后: 1.23E003
采用style: 0.00%格式化之后: 123456.79%
采用style: 0.00‰格式化之后: 1234567.89‰
0 0
原创粉丝点击