Int類型轉換為bigdecimal類型:先將int轉為String,再通過BigDecimal的構造方法去創建
BigDecimal price = new BigDecimal(String str);
Bigdecimal類型相加
BigDecimal newDeposit=price.add(oldDecimal);
擴充
add(BigDecimal)BigDecimal對象中的值相加,然后返回這個對象。
subtract(BigDecimal)BigDecimal對象中的值相減,然后返回這個對象。
multiply(BigDecimal)BigDecimal對象中的值相乘,然后返回這個對象。
divide(BigDecimal)BigDecimal對象中的值相除,然后返回這個對象。
做除法時可以加入參數,確保精確到小數點后幾位
需要加入具體的位數和保留模式
就是給divide設置精確的小數點divide(xxxxx,2, BigDecimal.ROUND_HALF_EVEN)
BigDecimal定義了一下舍入模式,只有在作除法運算或四舍五入時才用到舍入模式,下面簡單介紹,詳細請查閱J2se API文檔
static int
**ROUND_CEILING**
Rounding mode to round towards positive infinity.
向正無窮方向舍入
static int
**ROUND_DOWN**
Rounding mode to round towards zero.
向零方向舍入
static int
**ROUND_FLOOR**
Rounding mode to round towards negative infinity.
向負無窮方向舍入
static int
**ROUND_HALF_DOWN**
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
向(距離)最近的一邊舍入,除非兩邊(的距離)是相等,如果是這樣,向下舍入, 例如1.55 保留一位小數結果為1.5
static int
**ROUND_HALF_EVEN**
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
向(距離)最近的一邊舍入,除非兩邊(的距離)是相等,如果是這樣,如果保留位數是奇數,使用ROUND_HALF_UP ,如果是偶數,使用ROUND_HALF_DOWN
static int
**ROUND_HALF_UP**
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
向(距離)最近的一邊舍入,除非兩邊(的距離)是相等,如果是這樣,向上舍入, 1.55保留一位小數結果為1.6
static int
**ROUND_UNNECESSARY**
Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary.
計算結果是精確的,不需要舍入模式
static int
**ROUND_UP**
Rounding mode to round away from zero.
向遠離0的方向舍入
toString()將BigDecimal對象的數值轉換成字符串。
doubleValue()將BigDecimal對象中的值以雙精度數返回。
floatValue()將BigDecimal對象中的值以單精度數返回。
longValue()將BigDecimal對象中的值以長整數返回。
intValue()將BigDecimal對象中的值以整數返回。