这个问题困惑了很久了,一直没有解决。
假如我要把一个包含25位整数,6位小数的大数字格式化成 #,###的形式,
用jdk1.42自带的API能不能实现?
如果数字更大呢? BigDecimal计算的时候不会丢精度,最后计算结果用BigDecimal.toString()就是精确值,
但是用了Format后就会丢精度了,不知道怎么解决。

解决方案 »

  1.   

    import java.text.*;
    /**
     * <p>Title: </p>
     * <p>Description: </p>
     * <p>Copyright: Copyright (c) 2005</p>
     * <p>Company: </p>
     * @author not attributable
     * @version 1.0
     */public class CustomFormat {
      public CustomFormat() {
      }
      public static void main(String[] args) {
        // The 0 symbol shows a digit or 0 if no digit present
        NumberFormat formatter = new DecimalFormat("000000");
        String s = formatter.format(-1234.567);  // -001235
        // notice that the number was rounded up    // The # symbol shows a digit or nothing if no digit present
        formatter = new DecimalFormat("##");
        s = formatter.format(-1234.567);         // -1235
        s = formatter.format(0);                 // 0
        formatter = new DecimalFormat("##00");
        s = formatter.format(0);                 // 00
        // The . symbol indicates the decimal point
        formatter = new DecimalFormat(".00");
        s = formatter.format(-.567);             // -.57
        formatter = new DecimalFormat("0.00");
        s = formatter.format(-.567);             // -0.57
        formatter = new DecimalFormat("#.#");
        s = formatter.format(-1234.567);         // -1234.6
        formatter = new DecimalFormat("#.######");
        s = formatter.format(-1234.567);         // -1234.567
        formatter = new DecimalFormat(".######");
        s = formatter.format(-1234.567);         // -1234.567
        formatter = new DecimalFormat("#.000000");
        s = formatter.format(-1234.567);         // -1234.567000
        // The , symbol is used to group numbers
        formatter = new DecimalFormat("#,###,###");
        s = formatter.format(-1234.567);         // -1,235
        s = formatter.format(-1234567.890);      // -1,234,568    // The ; symbol is used to specify an alternate pattern for negative values
        formatter = new DecimalFormat("#;(#)");
        s = formatter.format(-1234.567);         // (1235)    // The ' symbol is used to quote literal symbols
        formatter = new DecimalFormat("'#'#");
        s = formatter.format(-1234.567);         // -#1235
        formatter = new DecimalFormat("'abc'#");
        s = formatter.format(-1234.567);         // -abc1235  }}
      

  2.   

    我目前用的解决办法是把整数部分和小数部分分别用一个BigDecimal保存,这样再分别格式化这两个BigDecimal,这样精度就不会损失了。
    还是感谢楼上的。要不真没有人发言。