# java小数会有偏差_Java中float类型自动转double类型会有误差

public class Arith {

private static final int DEF_DIV_SCALE = 10;

private Arith() {

}

/**

* 提供精确的加法运算

* @param args

*/

public static double add(double v1, double v2) {

BigDecimal b1 = new BigDecimal(Double.toString(v1));

BigDecimal b2 = new BigDecimal(Double.toString(v2));

}

/**

* 提供了精确的减法运算

*

* @param args

*/

public static double sub(double v1, double v2) {

BigDecimal b1 = new BigDecimal(Double.toString(v1));

BigDecimal b2 = new BigDecimal(Double.toString(v2));

return b1.subtract(b2).doubleValue();

}

/**

* 提供了精确的乘法运算

* @param args

*/

public static double mul(double v1, double v2) {

BigDecimal b1 = new BigDecimal(Double.toString(v1));

BigDecimal b2 = new BigDecimal(Double.toString(v2));

return b1.multiply(b2).doubleValue();

}

/**

* 提供了(相对)精确的除法运算，当发生除不尽的情况时，精确到

* 小数点以後１10位

* @param args

*/

public static double div(double v1, double v2) {

return div(v1, v2, DEF_DIV_SCALE);

}

/**

* 提供了(相对)精确的除法运算，当发生除不尽的情况时，由scale参数指定

* 精度，以後的数字四舍五入

* @param args

*/

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(Double.toString(v1));

BigDecimal b2 = new BigDecimal(Double.toString(v2));

return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();

}

/**

* 提供了精确的小数位四舍五入处理

* @param args

*/

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_DOWN).doubleValue();

}

public static void main(String[] args) {

System.out.println(sub(6.4523423, 1.2321231));

System.out.println(mul(6.4523423, 3.7865765));

System.out.println(div(6.4523423, 3.7865765, 5));

System.out.println(round(3.7865765, 5));

}

}

06-26 2308

06-06 2444
05-21 4万+
05-27 6458
08-25 1868
01-07 4062
12-12 279
06-30 1529
04-14 7182
12-05 2933
04-07 138
07-02 4027
05-18 166
08-21 773
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客