BigDecimal的加法源码如下,都是有返回值的。
因为BigInteger与BigDecimal都是不可变的(immutable)的,在进行每一步运算时,都会产生一个新的对象,所以 a.add(b)虽然做了加法操作,但是a并没有保存加操作后的值,正确的用法应该是a=a.add(b); 减乘除操作也是一样的返回一个新的BigDecimal对象。
public BigDecimal add(BigDecimal augend) {
long xs =this.intCompact; //整型数字表示的BigDecimal,例a的intCompact值为122long ys = augend.intCompact;//同上//初始化BigInteger的值,intVal为BigDecimal的一个BigInteger类型的属性BigInteger fst = (this.intCompact !=INFLATED) ?null :this.intVal;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)//判断有无溢出//返回使用BigDecimal的静态工厂方法得到的BigDecimal实例return BigDecimal.valueOf(sum,rscale);}if (fst ==null)fst =BigInteger.valueOf(xs);//BigInteger的静态工厂方法if (snd ==null)snd =BigInteger.valueOf(ys);BigInteger sum =fst.add(snd);//返回通过其他构造方法得到的BigDecimal对象return (fst.signum == snd.signum) ?new BigDecimal(sum,INFLATED, rscale, 0) :new BigDecimal(sum,compactValFor(sum),rscale, 0);
}