我有一个bigDecimal的数,比如
BigDecimal aa = new BigDecimal("1234567.12");
现在需要用String format转换成String类型的 1,234,567.12输出
怎么实现?急,在线等

解决方案 »

  1.   

    public static void main(String[] args) {
    BigDecimal aa = new BigDecimal("1234567.12");
    System.out.println(addComma(aa.toString()));
    }
    /**
    * 在数字型字符串千分位加逗号
    * @param str
    * @return
    */
    public static String addComma(String str){
    boolean neg = false;
    if (str.startsWith("-")){  //处理负数
    str = str.substring(1);
    neg = true;
    }
    String tail = null;
    if (str.indexOf('.') != -1){ //处理小数点
    tail = str.substring(str.indexOf('.'));
    str = str.substring(0, str.indexOf('.'));
    }
    StringBuilder sb = new StringBuilder(str);
    sb.reverse();
    for (int i = 3; i < sb.length(); i += 4){
    sb.insert(i, ',');
    }
    sb.reverse();
    if (neg){
    sb.insert(0, '-');
    }
    if (tail != null){
    sb.append(tail);
    }
    return sb.toString();
    }
      

  2.   

    不能写个方法format,需要类似于String.format("匹配表达式",aa)一行代码搞定
      

  3.   

    看MessageFormat的例子,就是为了处理楼主的这种要求的。
      

  4.   

    public static void main(String[] args) {
    BigDecimal aa = new BigDecimal("1234567.12");
    System.out.println(String.format("%1$,09.2f", aa));
    }
      

  5.   

    DecimalFormat是专门处理这种需求的
    String pattern="###,###.###";
    DecimalFormat myFormatter = new DecimalFormat(pattern);
    String output = myFormatter.format(value);
    System.out.println(value + " " + pattern + " " + output);The pound sign (#) denotes a digit, the comma is a placeholder for the grouping separator, and the period is a placeholder for the decimal separator.
      

  6.   


    把二楼的方法改个名字,处理一下BigDecimal的小数点问题不就可以了吗?