小数的加减乘除
今天修改项目的时候,突然发现版本号的递增出现了问题,本来应该是当前版本号 + 0.1 = 递增后的版本号,结果获得的版本号出现了很多的小数。
例如:
public class Test04 {
public static void main(String[] args) {
Float f1 = 1.7f;
Float f2 = 0.1f;
Float f3 = f1 + f2;
System.out.println("f1 + f2 = "+f3);
}
}
输出结果:
因此,小数加减乘除建议用BigDecimal;
import java.math.BigDecimal;
public class Test04 {
public static void main(String[] args) {
//小数加减乘除用BigDecimal
BigDecimal b1 = new BigDecimal("1.8");
BigDecimal b2 = new BigDecimal("0.1");
BigDecimal b3 = b1.add(b2);//小数相加
BigDecimal b4 = b1.subtract(b2);//小数相减
BigDecimal b5 = b1.multiply(b2);//小数相乘
System.out.println("1.8 + 0.1 = " + b3);
System.out.println("1.8 - 0.1 = " + b4);
System.out.println("1.8 * 0.1 = " + b5);
}
}
输出结果: