当数据的数据类型为BigDecimal时,对数据进行加减乘除的操作,操作方法如下:
加法:add
减法:subtract
乘法:multiply
除法:divide
但是使用方法时需要特别注意,BigDecimal类型的数据a
当执行a.add(b)后,a的值发生了变化,相当于a=a+b的操作。
借用网上看到的资料:
分析与源码
查看BigDecimal源码
/**
* If the absolute value of the significand of this BigDecimal is
* less than or equal to {@code Long.MAX_VALUE}, the value can be
* compactly stored in this field and used in computations.
*/
private final transient long intCompact;
/**
* The scale of this BigDecimal, as returned by {@link #scale}.
*
* @serial
* @see #scale
*/
private final int scale; // Note: this may have any value, so
// calculations must be done in longs
可以发现,其实BigDecimal的实现就是一个long加上一个缩放等级, 对BigDecimal的操作都是对值进行操作,不会改变原来对象的值
所以操作时,用新的对象来接收,处理时处理新的对象,不会将源数据变更:
BigDecimal bigDecimal1 = new BigDecimal("1");
BigDecimal bigDecimal2 = new BigDecimal("2");
bigDecimal1.multiply(bigDecimal2);
bigDecimal1.add(bigDecimal2);
bigDecimal1.subtract(bigDecimal2);
bigDecimal1.divide(bigDecimal2);