用如下程序测试java中对小数位的四舍五入:public class Hello4 {
  public static void main(String[] args) {
    // 四舍五入到小数点后一位(正常)
    String temp = "#,##0.0";
    String s1 = new java.text.DecimalFormat(temp).format(11.2345);
    System.out.println(s1);    // 四舍五入到小数点后两位(正常)
    temp = "#,##0.00";
    s1 = new java.text.DecimalFormat(temp).format(11.2345);
    System.out.println(s1);    // 四舍五入到小数点后三位(出错)
    temp = "#,##0.000";
    s1 = new java.text.DecimalFormat(temp).format(11.2345);
    System.out.println(s1);    // 四舍五入到小数点后三位(正常)
    temp = "#,##0.000";
    s1 = new java.text.DecimalFormat(temp).format(11.23455);
    System.out.println(s1);
  }
}发现如下结果输出:
11.2
11.23
11.234
11.235不太明白, 请大家指教为何第三行输出的数不符合预期值呢???
有什么其它的决办法???

解决方案 »

  1.   

    取小数点后位数可以用BigDecimal来取,如下代码可以得到你想要得值:import java.math.BigDecimal;public class Hello4 {
        public static void main(String[] args) {      double s = 0;
          s = round(11.2345,3);
          System.out.println(s);
        }
        
        public static double round(double v,int scale){
            if(scale<0){
                throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
            }
            BigDecimal b = new BigDecimal(Double.toString(v));
            BigDecimal one = new BigDecimal("1");
            return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
        }
      }
      

  2.   

    怎么不是四舍五入?ROUND_HALF_UP不是四舍五入吗?