BigDecimal
普通类型计算
public class Test{ public static void main(String[] args) { System.out.println(0.06+0.01); System.out.println(1.0-0.42); System.out.println(4.015*100); System.out.println(303.1/1000); }}
输出
0.069999999999999990.5800000000000001401.499999999999940.30310000000000004
BigDecimal类
public class BigDecimalUilt { /** * 提供精确加法计算的add方法 * @param value1 被加数 * @param value2 加数 * @return 两个参数的和 */ public static double add(double value1,double value2){ BigDecimal b1 = new BigDecimal(Double.valueOf(value1)); BigDecimal b2 = new BigDecimal(Double.valueOf(value2)); return b1.add(b2).doubleValue(); } /** * 提供精确减法运算的sub方法 * @param value1 被减数 * @param value2 减数 * @return 两个参数的差 */ public static double sub(double value1,double value2){ BigDecimal b1 = new BigDecimal(Double.valueOf(value1)); BigDecimal b2 = new BigDecimal(Double.valueOf(value2)); return b1.subtract(b2).doubleValue(); } /** * 提供精确乘法运算的mul方法 * @param value1 被乘数 * @param value2 乘数 * @return 两个参数的积 */ public static double mul(double value1,double value2){ BigDecimal b1 = new BigDecimal(Double.valueOf(value1)); BigDecimal b2 = new BigDecimal(Double.valueOf(value2)); return b1.multiply(b2).doubleValue(); } /** * 提供精确的除法运算方法div * @param value1 被除数 * @param value2 除数 * @param scale 精确范围 * @return 两个参数的商 * @throws IllegalAccessException */ public static double div(double value1,double value2,int scale) throws IllegalAccessException{ //如果精确范围小于0,抛出异常信息 if(scale<0){ throw new IllegalAccessException("精确度不能小于0"); } BigDecimal b1 = new BigDecimal(Double.valueOf(value1)); BigDecimal b2 = new BigDecimal(Double.valueOf(value2)); return b1.divide(b2, scale).doubleValue(); }}
add(BigDecimal augend)方法源码
public BigDecimal add(BigDecimal augend) { long xs =this.intCompact; //整型数字表示的BigDecimal,例a的intCompact值为122 long ys = augend.intCompact;//同上 BigInteger fst = (this.intCompact !=INFLATED) ?null :this.intVal;//初始化BigInteger的值,intVal为BigDecimal的一个BigInteger类型的属性 BigInteger snd =(augend.intCompact !=INFLATED) ?null : augend.intVal; int rscale =this.scale;//小数位数 long sdiff = (long)rscale - augend.scale;//小数位数之差 if (sdiff != 0) {//取小数位数多的为结果的小数位数 if (sdiff < 0) { int raise =checkScale(-sdiff); rscale =augend.scale; if (xs ==INFLATED || (xs = longMultiplyPowerTen(xs,raise)) ==INFLATED) fst =bigMultiplyPowerTen(raise); }else { int raise =augend.checkScale(sdiff); if (ys ==INFLATED ||(ys =longMultiplyPowerTen(ys,raise)) ==INFLATED) snd = augend.bigMultiplyPowerTen(raise); } } if (xs !=INFLATED && ys !=INFLATED) { long sum = xs + ys; if ( (((sum ^ xs) &(sum ^ ys))) >= 0L)//判断有无溢出 return BigDecimal.valueOf(sum,rscale);//返回使用BigDecimal的静态工厂方法得到的BigDecimal实例 } if (fst ==null) fst =BigInteger.valueOf(xs);//BigInteger的静态工厂方法 if (snd ==null) snd =BigInteger.valueOf(ys); BigInteger sum =fst.add(snd); return (fst.signum == snd.signum) ?new BigDecimal(sum,INFLATED, rscale, 0) : new BigDecimal(sum,compactValFor(sum),rscale, 0);//返回通过其他构造方法得到的BigDecimal对象}