double类型的两个数相减可能存在误差,比如System.out.println(2099 - 1999.9);的结果为99.09999999999991
可以用BigDecimal解决:
public class TestDouble {
//两个Double数相减
public static Double sub(Double d1, Double d2) {
if (d1 == null || d2 == null) {
return null;
}
BigDecimal b1 = new BigDecimal(d1.toString());
BigDecimal b2 = new BigDecimal(d2.toString());
return b1.subtract(b2).doubleValue();
}
//两个Double数相加
public static Double add(Double d1, Double d2) {
if (d1 == null || d2 == null) {
return null;
}
BigDecimal b1 = new BigDecimal(d1.toString());
BigDecimal b2 = new BigDecimal(d2.toString());
return b1.add(b2).doubleValue();
}
//两个Double数相除,并保留scale位小数
public static Double div(Double d1, Double d2, int scale) {
if (d1 == null || d2 == null || scale < 0) {
return null;
}
BigDecimal b1 = new BigDecimal(d1.toString());
BigDecimal b2 = new BigDecimal(d2.toString());
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
// 两个Double数相乘
public static Double mul(Double d1, Double d2) {
if (d1 == null || d2 == null) {
return null;
}
BigDecimal b1 = new BigDecimal(d1.toString());
BigDecimal b2 = new BigDecimal(d2.toString());
return b1.multiply(b2).doubleValue();
}
/**
* 遇到.5的情况时往上近似
*
* @param d
* @param scale
* @return
*/
public static Double setDoubleScale(Double d, int scale) {
if (d == null || scale < 0) {
return null;
}
BigDecimal b = new BigDecimal(d);
return b.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static void main(String[] args) {
Double d1 = 2099d;
Double d2 = 1999.999;
System.out.println(d1 - d2);
System.out.println(sub(d1, d2));
System.out.println("------------------------------------");
System.out.println(d1 * d2);
System.out.println(mul(d1, d2));
System.out.println("------------------------------------");
System.out.println(d1/d2);
System.out.println(div(d1,d2,4));
}
}
结果:
99.00099999999998
99.001
------------------------------------
4197997.901
4197997.901
------------------------------------
1.0495005247502625
1.0495