Bigdecimal類型使用 保留小數位

bigdecimal 保留小數位

實際開發中,會出現數值爲空的狀況,這時類的getter和setter方法應該判斷是否傳入爲空或者直接在Bigdecimal 類型屬性上初始化,如:html

 private BigDecimal income = new BigDecimal(0);  //收入
 private BigDecimal cess = new BigDecimal(0);  //稅額
 private BigDecimal comm = new BigDecimal(0);  // 總費用 less

 BigDecimal類型若是須要運算則要轉換類型爲double或Double才行,計算完成後再轉換回Bigdecimal類型,這時BigDecimal裏面的值有多是不少位小數位,若是但願無論計算結果,當我得到某一對象Bigdecimal類型屬性的值時,統一都是2位小數時,要控制該屬性的getter或setter方法,如:ui

控制getter() ,須要配合上面的屬性字段的初始化this

public BigDecimal getCess() {
  return cess.setScale(2, BigDecimal.ROUND_HALF_UP);
 }spa

或者控制setter()
 public void setCess(BigDecimal cess) {
    if(null == cess){
      this.cess = cess.setScale(2, BigDecimal.ROUND_HALF_UP);
    }else{
      this.cess = null;
    }
 }rest

複製代碼

public class test1_format {

    public static void main(String[] args) {
        BigDecimal decimal = new BigDecimal("1.12345");
        System.out.println(decimal);
        BigDecimal setScale = decimal.setScale(4,BigDecimal.ROUND_HALF_DOWN);
        System.out.println(setScale);
        
        BigDecimal setScale1 = decimal.setScale(4,BigDecimal.ROUND_HALF_UP);
        System.out.println(setScale1);
    }
}

複製代碼

 

參數定義orm

ROUND_CEILING 
Rounding mode to round towards positive infinity. 
向正無窮方向舍入 

ROUND_DOWN 
Rounding mode to round towards zero. 
向零方向舍入 

ROUND_FLOOR 
Rounding mode to round towards negative infinity. 
向負無窮方向舍入 

ROUND_HALF_DOWN 
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down. 
向(距離)最近的一邊舍入,除非兩邊(的距離)是相等,若是是這樣,向下舍入, 例如1.55 保留一位小數結果爲1.5 

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 


ROUND_HALF_UP 
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. 
向(距離)最近的一邊舍入,除非兩邊(的距離)是相等,若是是這樣,向上舍入, 1.55保留一位小數結果爲1.6 


ROUND_UNNECESSARY 
Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary. 
計算結果是精確的,不須要舍入模式 


ROUND_UP 
Rounding mode to round away from zero. 
向遠離0的方向舍入htm

相關文章
相關標籤/搜索