@contribute
2016-02-02T06:43:04.000000Z
字数 1999
阅读 1550
java
DecimalFormat df1 = new DecimalFormat(pattern);
占位符可以使用0和#两种.
当使用0的时候会严格按照样式来进行匹配,不够的时候会补0。使用#时会将前后的0进行忽略。
DecimalFormat df2 = new DecimalFormat("####.####");System.out.println(df2.format(2.4)); // 2.4System.out.println(df2.format(2.34333)); // 2.3433System.out.println(df2.format(133332.4)); // 133332.4System.out.println(df2.format(133332.3333334)); // 133332.3333DecimalFormat df3 = new DecimalFormat("0000.0000");System.out.println(df3.format(12.34)); // 0012.3400System.out.println(df3.format(22.34231D)); // 0022.3423System.out.println(df3.format(12322.31D)); // 12322.3100System.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.10System.out.println(df.format(1.333));// 1.333System.out.println(df.format(1.55555));// 1.5556// Integer代表整数位df.setMinimumIntegerDigits(5);df.setMinimumIntegerDigits(3);// 设置小数点后最小位数,不够的时候补0System.out.println(df.format(22.12345678));// 022.1235System.out.println(df.format(4444.5555555)); // 4,444.5556System.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));// 15a5566System.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%}