/** * 提供精确的小数位四舍五入处理。 * @param v 需要四舍五入的数字 * @param scale 小数点后保留几位 * @return 四舍五入后的结果 */ 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(); }
BigDecimal b = new BigDecimal(Double.toString(v)); BigDecimal one = new BigDecimal("1"); return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); 是利用什么方法啊,作用是什么啊。能描述详细一点吗?我想多了解一下原理谢谢
public static double r(double d, int i) { double dd = d * Math.pow(10, i);
dd = Math.round(dd);
dd = dd / Math.pow(10, i);
return dd; }
改造了一下/** * 提供精确的小数位四舍五入处理。 * * @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).doubleValue(); return df1.format(t).toString(); }
* 提供精确的小数位四舍五入处理。 * @param v 需要四舍五入的数字 * @param scale 小数点后保留几位 * @return 四舍五入后的结果 */ 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(); }
是利用什么方法啊,作用是什么啊。能描述详细一点吗?我想多了解一下原理谢谢
{
double dd = d * Math.pow(10, i);
dd = Math.round(dd);
dd = dd / Math.pow(10, i);
return dd;
}
* 提供精确的小数位四舍五入处理。
*
* @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).doubleValue();
return df1.format(t).toString();
}