a.add(b);
System.out.println("aplus b is : " + a);
我们很容易会认为会输出:
construct with a Stringvalue: 1.22
a plus b is :3.44
但实际上a plus b is : 1.22
4.源码分析
4.1 valueOf(doubleval)方法
public static BigDecimalvalueOf(double val) {
// Reminder: a zero double returns '0.0', so we cannotfastpath
// to use the constant ZERO. This might be important enough to
// justify a factory approach, a cache, or a few private
// constants, later.
returnnew BigDecimal(Double.toString(val));//见3.1关于JDK描述的第三点 }
4.2 add(BigDecimal augend)方法
public BigDecimal add(BigDecimal augend) {
long xs =this.intCompact; //整型数字表示的BigDecimal,例a的intCompact值为122
long ys = augend.intCompact;//同上
BigIntegerfst = (this.intCompact !=INFLATED) ?null :this.intVal;//初始化BigInteger的值,intVal为BigDecimal的一个BigInteger类型的属性