我用以下代码取四舍五入值:
 /**
   * 四舍五入.
   * @param x double 源值.
   * @param y int 小数位数.
   * @return double 四舍五入后的值.
   * @author xujun
   * create 2004-11-19 16:07
   */
  public static double round (double x, int y) {
    if (x >= 0.0D) {
      x += 9.9999999999999995E-008D ;
    }
    else {
      x -= 9.9999999999999995E-008D ;
    }
    String formatstr = "################" ;
    if (y != 0) {
      formatstr += "." ;
      for (int i = 0 ; i < y ; i++) {
        formatstr += "#" ;
      }
    }
    String str = (new DecimalFormat (formatstr)).format (x) ;
    return Double.parseDouble (str) ;
  }
但是输入round(18.0/28.0,7)的时候返回的值是0.6428572而不是0.6428571。由于我的程序对数据的精度要求比较高,所以请大家给看看,解决办法有效的送分50!!!

解决方案 »

  1.   

    奇怪啊,你的修正x的算法
        if (x >= 0.0D) {
          x += 9.9999999999999995E-008D ;
        }
        else {
          x -= 9.9999999999999995E-008D ;
        }
    怎么跟y无关啊?
      

  2.   

    还有,即便固定是7,也应该是5E-008D,而不是9.9999999999999995E-008D吧?
      

  3.   

      public static double myRound (double x, int y) {
       int divided = 1;
       for(int i = 0; i < y; i++){
       x = x * 10;
       divided = divided * 10;
       }
       int dd = (int) x;
       if((int) (x * 10 - dd * 10) < 5){
       x = (double)dd / divided;
       }
       else{
       x = (double)(dd + 1) / divided;
       }
       return x;
      }
      

  4.   

    以前我用的一个寒暑,感觉挺好    public static double round(double f, int n) {
            f *= Math.pow(10, n);
            f = Math.round(f);
            f /= Math.pow(10, n);
            return f;
        }
      

  5.   

    简化一下:
      public static double myRound (double x, int y) {
       int divided = 1;
       for(int i = 0; i < y; i++){
       x = x * 10;
       divided = divided * 10;
       }
       return (double)((int) (x + .5d)) / divided;
      }
      

  6.   

    divided 用long型更好:
      public static double myRound (double x, int y) {
       long divided = 1;
       for(int i = 0; i < y; i++){
       x = x * 10;
       divided = divided * 10;
       }
       return (double)((long) (x + .5d)) / divided;
      }