java中用DecimalFormat df = new
DecimalFormat("#######0.00");进行四舍五入时,如果最后一位为5,则会直接舍掉,而不会入上去。如:12.515,得到得
结果将是12.51。解决方法:
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();
}
java中的浮点数类型float和double不能进行运算,遇到有些数据得到的数据不准确。如:3.121-1=3.1209999999998。解决方法:
public class Arith {
private static final int DEF_DIV_SCALE = 10;
/**
* 两个Double数相加
* @param v1
* @param v2
* @return Double
*/
public static Double add(Double v1,Double v2){
BigDecimal b1 = new BigDecimal(v1.toString());
BigDecimal b2 = new BigDecimal(v2.toString());
return b1.add(b2).doubleValue();
}
/**
* 两个Double数相减
* @param v1
* @param v2
* @return Double
*/
public static Double sub(Double v1,Double v2){
BigDecimal b1 = new BigDecimal(v1.toString());
BigDecimal b2 = new BigDecimal(v2.toString());
return b1.subtract(b2).doubleValue();
}
/**
* 两个Double数相乘
* @param v1
* @param v2
* @return Double
*/
public static Double mul(Double v1,Double v2){
BigDecimal b1 = new BigDecimal(v1.toString());
BigDecimal b2 = new BigDecimal(v2.toString());
return b1.multiply(b2).doubleValue();
}
/**
* 两个Double数相除
* @param v1
* @param v2
* @return Double
*/
public static Double div(Double v1,Double v2){
BigDecimal b1 = new BigDecimal(v1.toString());
BigDecimal b2 = new BigDecimal(v2.toString());
return b1.divide(b2,DEF_DIV_SCALE,BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 两个Double数相除,并保留scale位小数
* @param v1
* @param v2
* @param scale
* @return Double
*/
public static Double div(Double v1,Double v2,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(v1.toString());
BigDecimal b2 = new BigDecimal(v2.toString());
return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
}