一、格式化日期和时间
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiM4EDOxITM0EjMwMDM2EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
举例:
public void formatDateTime(){
DateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date date = new Date();
System.out.println(format.format(date));
}
结果:2016年03月02日 14:13:08
二、格式化数字
举例:
public static void formatNumber(){
double d = ;
DecimalFormat format = new DecimalFormat("##.###");
System.out.println(format.format(d));//会进行四舍五入
format.applyPattern("##.###%");
System.out.println(format.format(d));
format.applyPattern("###,###.000");
System.out.println(format.format(d));
}
结果:
34563.889
3456388.888%
34,563.889
三、常规类型的格式化
举例:
public static void formatString(){
String str=null;
str=String.format("Hi,%s,%s,%s", "张三","李四","王五");
System.out.println(str);
System.out.printf("字母a的大写是:%c %n", 'A');
System.out.printf("3>7的结果是:%b %n", >);
System.out.printf("100的一半是:%d %n", /);
System.out.printf("100的16进制数是:%x %n", );
System.out.printf("100的8进制数是:%o %n", );
System.out.printf("50元的书打8.5折扣是:%f 元%n", *0.);
System.out.printf("上面价格的16进制数是:%a %n", *0.);
System.out.printf("上面价格的指数表示:%e %n", *0.);
System.out.printf("上面价格的指数和浮点数结果的长度较短的是:%g %n", *0.);
System.out.printf("上面的折扣是%d%% %n", );
System.out.printf("字母A的散列码是:%h %n", 'A');
}
结果:
Hi,张三,李四,王五
字母a的大写是:A
3>7的结果是:false
100的一半是:50
100的16进制数是:64
100的8进制数是:144
50元的书打8.5折扣是:42.500000 元
上面价格的16进制数是:0x1.54p5
上面价格的指数表示:4.250000e+01
上面价格的指数和浮点数结果的长度较短的是:42.5000
上面的折扣是85%
字母A的散列码是:41