<<  java中的集合 | 首 页 | n=n++;  >>

java中的四舍五入实现

[ JAVA ]

 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(v);
  BigDecimal one = new BigDecimal("1");
  return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
 }

利用BigDecimal类中提供的除法。

 BigDecimaldivide(BigDecimal divisor, int scale, int roundingMode)
          Returns a BigDecimal whose value is (this / divisor), and whose scale is as specified.

参数:

static intROUND_HALF_DOWN
          Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
static intROUND_HALF_EVEN
          Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
static intROUND_HALF_UP
          Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.






so help me to get where i belong......i love u...forever....

评论

    发表评论

     姓名:
     E-mail:
     地址: