[关闭]
@contribute 2016-02-02T06:43:04.000000Z 字数 1999 阅读 1321

DecimalFormat用法

java


  1. DecimalFormat df1 = new DecimalFormat(pattern);

1 pattern设计

占位符可以使用0和#两种.

1.1 使用#与0

当使用0的时候会严格按照样式来进行匹配,不够的时候会补0。使用#时会将前后的0进行忽略。

  1. DecimalFormat df2 = new DecimalFormat("####.####");
  2. System.out.println(df2.format(2.4)); // 2.4
  3. System.out.println(df2.format(2.34333)); // 2.3433
  4. System.out.println(df2.format(133332.4)); // 133332.4
  5. System.out.println(df2.format(133332.3333334)); // 133332.3333
  6. DecimalFormat df3 = new DecimalFormat("0000.0000");
  7. System.out.println(df3.format(12.34)); // 0012.3400
  8. System.out.println(df3.format(22.34231D)); // 0022.3423
  9. System.out.println(df3.format(12322.31D)); // 12322.3100
  10. System.out.println(df3.format(12322.34231D)); // 12322.3423

1.2 使用Fraction和Integer

  1. public static void testFractionAndInteger() {
  2. DecimalFormat df = new DecimalFormat();
  3. System.out.println(df.format(1.5555555));// 1.556
  4. // Fraction代表小数位
  5. df.setMaximumFractionDigits(4);
  6. df.setMinimumFractionDigits(2);
  7. System.out.println(df.format(1.1));// 1.10
  8. System.out.println(df.format(1.333));// 1.333
  9. System.out.println(df.format(1.55555));// 1.5556
  10. // Integer代表整数位
  11. df.setMinimumIntegerDigits(5);
  12. df.setMinimumIntegerDigits(3);
  13. // 设置小数点后最小位数,不够的时候补0
  14. System.out.println(df.format(22.12345678));// 022.1235
  15. System.out.println(df.format(4444.5555555)); // 4,444.5556
  16. System.out.println(df.format(666666.5555555)); // 666,666.5556
  17. }

1.3 使用DecimalFormatSymbols

  1. public static void testDecimalFormatSymbols() {
  2. DecimalFormat df = new DecimalFormat();
  3. df.setGroupingSize(4);// 设置每四个一组
  4. System.out.println(df.format(15522323566L));
  5. DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();
  6. dfs.setDecimalSeparator(';');// 设置小数点分隔符
  7. dfs.setGroupingSeparator('a');// 设置分组分隔符
  8. df.setDecimalFormatSymbols(dfs);
  9. System.out.println(df.format(155566));// 15a5566
  10. System.out.println(df.format(11.22));// 11;22
  11. // 取消分组
  12. df.setGroupingUsed(false);
  13. System.out.println(df.format(155566));
  14. }

1.3 使用百分号

  1. public static void testPercent() {
  2. DecimalFormat df = new DecimalFormat();
  3. df.applyPattern("##.##%");
  4. System.out.println(df.format(1.220));// 122%
  5. System.out.println(df.format(11.22));// 1122%
  6. System.out.println(df.format(0.22));// 22%
  7. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注