java中小数的加减乘除
单价 * 数量 * 折扣=应收金额 或者正常的加减,会突然出现很多个小数
public static void main(String[] args) { double kk = 3.14; kk += 0.37; float ff = 3.14f; ff += 0.37f; System.out.println("double kk =" + kk); System.out.println("float ff =" + ff); }
输出结果:
double kk =3.5100000000000002
float ff =3.5100002
小数加减乘除建议用BigDecimal;
public static void main(String[] args) { //小数加减乘除用BigDecimal BigDecimal b1 = new BigDecimal("3.14"); BigDecimal b2 = new BigDecimal("0.37"); BigDecimal b3 = b1.add(b2);// BigDecimal b4 = b1.subtract(b2);// BigDecimal b5 = b1.multiply(b2); System.out.println("3.14 + 0.37 = " + b3); System.out.println("3.14 - 0.37 = " + b4); System.out.println("3.14 * 0.37 = " + b5); } 输出: 3.14 + 0.37 = 3.51 3.14 - 0.37 = 2.77 3.14 * 0.37 = 1.1618
JDK中BigDecimal类方法说明:https://www.yiibai.com/java/math/java_math_bigdecimal.html
坚持每天进步,自律改变自己