BigDecimal為什么可以不丟失精度?
在金融領域,為了保證數據的精度,往往會使用BigDecimal。本文就來探討下為什么BigDecimal可以保證精度不丟失。
類介紹
首先來看一下BigDecimal的類聲明以及幾個屬性:
public class BigDecimal extends Number implements Comparable<BigDecimal> {
// 該BigDecimal的未縮放值
private final BigInteger intVal;
// 精度,可以理解成小數點后的位數
private final int scale;
// BigDecimal中的十進制位數,如果位數未知,則為0(備用信息)
private transient int precision;
// Used to store the canonical string representation, if computed.
// 這個我理解就是存實際的BigDecimal值
private transient String stringCache;
// 擴大成long型數值后的值
private final transient long intCompact;
}
從例子入手
通過debug來發(fā)現源碼中的奧秘是了解類運行機制很好的方式。請看下面的testBigDecimal方法:
@Test
public void testBigDecimal() {
BigDecimal bigDecimal1 = BigDecimal.valueOf(2.36);
BigDecimal bigDecimal2 = BigDecimal.valueOf(3.5);
BigDecimal resDecimal = bigDecimal1.add(bigDecimal2);
System.out.println(resDecimal);
}
在執(zhí)行了BigDecimal.valueOf(2.36)后,查看debug信息可以發(fā)現上述提到的幾個屬性被賦了值:
圖片
接下來進到add方法里面,看看它是怎么計算的:
/**
* Returns a BigDecimal whose value is (this + augend),
* and whose scale is max(this.scale(), augend.scale()).
*/
public BigDecimal add(BigDecimal augend) {
if (this.intCompact != INFLATED) {
if ((augend.intCompact != INFLATED)) {
return add(this.intCompact, this.scale, augend.intCompact, augend.scale);
} else {
return add(this.intCompact, this.scale, augend.intVal, augend.scale);
}
} else {
if ((augend.intCompact != INFLATED)) {
return add(augend.intCompact, augend.scale, this.intVal, this.scale);
} else {
return add(this.intVal, this.scale, augend.intVal, augend.scale);
}
}
}
看一下傳進來的值:
圖片
進入上面代碼塊第8行的add方法:
private static BigDecimal add(final long xs, int scale1, final long ys, int scale2) {
long sdiff = (long) scale1 - scale2;
if (sdiff == 0) {
return add(xs, ys, scale1);
} else if (sdiff < 0) {
int raise = checkScale(xs,-sdiff);
long scaledX = longMultiplyPowerTen(xs, raise);
if (scaledX != INFLATED) {
return add(scaledX, ys, scale2);
} else {
BigInteger bigsum = bigMultiplyPowerTen(xs,raise).add(ys);
return ((xs^ys)>=0) ? // same sign test
new BigDecimal(bigsum, INFLATED, scale2, 0)
: valueOf(bigsum, scale2, 0);
}
} else {
int raise = checkScale(ys,sdiff);
long scaledY = longMultiplyPowerTen(ys, raise);
if (scaledY != INFLATED) {
return add(xs, scaledY, scale1);
} else {
BigInteger bigsum = bigMultiplyPowerTen(ys,raise).add(xs);
return ((xs^ys)>=0) ?
new BigDecimal(bigsum, INFLATED, scale1, 0)
: valueOf(bigsum, scale1, 0);
}
}
}
這個例子中,該方法傳入的參數分別是:xs=236,scale1=2,ys=35,scale2=1
該方法首先計算scale1 - scale2,根據差值走不同的計算邏輯,這里求出來是1,所以進入到最下面的else代碼塊(這塊是關鍵):
首先17行校驗了一下數值范圍
18行將ys擴大了10的n次倍,這里n=raise=1,所以返回的scaledY=350
接著就進入到20行的add方法:
private static BigDecimal add(long xs, long ys, int scale){
long sum = add(xs, ys);
if (sum!=INFLATED)
return BigDecimal.valueOf(sum, scale);
return new BigDecimal(BigInteger.valueOf(xs).add(ys), scale);
}
這個方法很簡單,就是計算和,然后返回BigDecimal對象:
圖片
結論
所以可以得出結論:BigDecimal在計算時,實際會把數值擴大10的n次倍,變成一個long型整數進行計算,整數計算時自然可以實現精度不丟失。同時結合精度scale,實現最終結果的計算。