@contribute
2016-02-02T06:43:04.000000Z
字数 1999
阅读 1429
java
DecimalFormat df1 = new DecimalFormat(pattern);
占位符可以使用0和#两种.
当使用0的时候会严格按照样式来进行匹配,不够的时候会补0。使用#时会将前后的0进行忽略。
DecimalFormat df2 = new DecimalFormat("####.####");
System.out.println(df2.format(2.4)); // 2.4
System.out.println(df2.format(2.34333)); // 2.3433
System.out.println(df2.format(133332.4)); // 133332.4
System.out.println(df2.format(133332.3333334)); // 133332.3333
DecimalFormat df3 = new DecimalFormat("0000.0000");
System.out.println(df3.format(12.34)); // 0012.3400
System.out.println(df3.format(22.34231D)); // 0022.3423
System.out.println(df3.format(12322.31D)); // 12322.3100
System.out.println(df3.format(12322.34231D)); // 12322.3423
public static void testFractionAndInteger() {
DecimalFormat df = new DecimalFormat();
System.out.println(df.format(1.5555555));// 1.556
// Fraction代表小数位
df.setMaximumFractionDigits(4);
df.setMinimumFractionDigits(2);
System.out.println(df.format(1.1));// 1.10
System.out.println(df.format(1.333));// 1.333
System.out.println(df.format(1.55555));// 1.5556
// Integer代表整数位
df.setMinimumIntegerDigits(5);
df.setMinimumIntegerDigits(3);
// 设置小数点后最小位数,不够的时候补0
System.out.println(df.format(22.12345678));// 022.1235
System.out.println(df.format(4444.5555555)); // 4,444.5556
System.out.println(df.format(666666.5555555)); // 666,666.5556
}
public static void testDecimalFormatSymbols() {
DecimalFormat df = new DecimalFormat();
df.setGroupingSize(4);// 设置每四个一组
System.out.println(df.format(15522323566L));
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();
dfs.setDecimalSeparator(';');// 设置小数点分隔符
dfs.setGroupingSeparator('a');// 设置分组分隔符
df.setDecimalFormatSymbols(dfs);
System.out.println(df.format(155566));// 15a5566
System.out.println(df.format(11.22));// 11;22
// 取消分组
df.setGroupingUsed(false);
System.out.println(df.format(155566));
}
public static void testPercent() {
DecimalFormat df = new DecimalFormat();
df.applyPattern("##.##%");
System.out.println(df.format(1.220));// 122%
System.out.println(df.format(11.22));// 1122%
System.out.println(df.format(0.22));// 22%
}