java中的四舍五入——几种四舍五入的写法

// 方式一:BigDecimal方式orm

double f = 3.1315;ci

BigDecimal b = new BigDecimal(字符串

new Double(f).toStringform

);方法

double f1 = b.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();im

注意:这里必定不要直接使用new BigDecimal(double)的构造方法, 而要使用new BigDecimal(new Double(1.1315).toString())的方式,否则会出现精确问题static

// 方式二:DecimalFormat方式di

//DecimalFormat默认采用了RoundingMode.HALF_EVEN这种类型,并且format以后的结果是一个字符串类型String字符

DecimalFormat df = new DecimalFormat("#.000");new

System.out.println(df.format(new BigDecimal(1.0145)));//1.014

System.out.println(df.format(new BigDecimal(1.1315)));//1.132

// 方式三:

double d = 3.1415926;

String result = String.format("%.2f", d);

// %.2f %. 表示 小数点前任意位数 2 表示两位小数 格式后的结果为f 表示浮点型。

//方法四:传统的Math.round四舍五入,改成支持指定精确位数的写法

Math.round(5.2644555 * 100) * 0.01d;

private static double myRound(double number,int index){

      double result = 0;

      double temp = Math.pow(10, index);

      result = Math.round(number*temp)/temp;

      return result;

相关文章
相关标签/搜索