2008年5月10日星期六

按照需要灵活保留小数点后小数位数

/**
* 提供精确的小数位四舍五入处理。
* @param v
* 需要四舍五入的数字
* @param scale
* 小数点后保留几位
* @return 四舍五入后的结果(字符串)
*/
public static String 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");
DecimalFormat df1 = new DecimalFormat("0.##########");
double t=b.divide(one, scale, BigDecimal.ROUND_HALF_UP).double();
return df1.format(t).toString();
}

没有评论:

发表评论