可以設定小數點的位元

來源:互聯網
上載者:User
public static double round(double value, int scale,int roundingmode) { BigDecimal bd = new BigDecimal(value); bd = bd.setScale(scale,roundingmode); double d = bd.doubleValue(); bd = null; return d; }

其中scale表示指定為幾位小數,roundingmode表示指定為何種取捨方式,比如四捨五入之類的。

roundingmode的取值如下:

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的方向舍入



BigDecimal.setScale()方法用于格式化小數點其中BigDecimal類用於精確的小數運算,比如商業用途的小數運算。
setScale(1)表示保留一位小數,預設用四捨五入方式 
setScale(1,BigDecimal.ROUND_DOWN)直接刪除多餘的小數位,如2.35會變成2.3 
setScale(1,BigDecimal.ROUND_UP)進位處理,2.35變成2.4 
setScale(1,BigDecimal.ROUND_HALF_UP)四捨五入,2.35變成2.4setScaler(1,BigDecimal.ROUND_HALF_DOWN)四捨五入,2.35變成2.3,如果是5則向下舍   注釋:1:scale指的是你小數點後的位元。比如123.456則score就是3.
score()就是BigDecimal類中的方法啊。
比如:BigDecimal b = new BigDecimal("123.456");b.scale(),返回的就是3.
2:
roundingMode是小數的保留模式。它們都是BigDecimal中的常量欄位,有很多種。
比如:BigDecimal.ROUND_HALF_UP表示的就是4舍5入。
3:
pubilc BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
的意思是說:我用一個BigDecimal對象除以divisor後的結果,並且要求這個結果保留有scale個小數位,roundingMode表示的就是保留模式是什麼,是四捨五入啊還是其它的,你可以自己選!

4:對於一般add、subtract、multiply方法的小數位格式化如下:

BigDecimal mData = new BigDecimal("9.655").setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println("mData=" + mData);
  ----結果:----- mData=9.66


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.