import java.math.BigDecimal;
/**
* @author
* @create 2021-09-19 10:27
* BigDecimal 学习笔记
* 位于java.math保重
* 作用:精确计算浮点数
*/
public class BigDecimalDemo {
public static void main(String[] args) {
double a = 1.0;
double b = 0.9;
// 精度丢失 0.09999999999999998
//原因是 double 和float 在java内存中存放的是近似值
System.out.println(a-b);
double result = (1.4 - 0.5) / 0.9;
//0.9999999999999999
System.out.println(result);
/*-----------------------减法-----------------------------------*/
//一定要传字符串 0.1,应为double 存放的近似值
BigDecimal subtract = new BigDecimal("1.0").subtract(new BigDecimal("0.9"));
//测试传double
BigDecimal bigDecimal = new BigDecimal(a);
// 0.09999999999999997779553950749686919152736663818359375
BigDecimal subtract1 = bigDecimal.subtract(new BigDecimal(b));
System.out.println(subtract);
System.out.println(subtract1);
/*-------------------------乘法-----------------------------------------*/
BigDecimal multiply = new BigDecimal("4").multiply(new BigDecimal("5"));
System.out.println("乘法:"+multiply);
/*--------------------------除法-----------------------------------------------*/
//除法注意保留小数,有可能除不尽会报错BigDecimal.ROUND_HALF_UP 四舍五入
//3.33
BigDecimal divide = new BigDecimal("10").divide(new BigDecimal("3"), 2, BigDecimal.ROUND_HALF_UP);
//5.000
BigDecimal divided = new BigDecimal("10").divide(new BigDecimal("2"), 3, BigDecimal.ROUND_HALF_UP);
// 0.5
BigDecimal dividedd = new BigDecimal("0.9").divide(new BigDecimal("2"), 1, BigDecimal.ROUND_HALF_UP);
System.out.println(dividedd);
}
}