Java.math.BigDecimal.round() 方法



描述

java.math.BigDecimal.round(MathContext mc) 根據 MathContext 設定返回一個已舍入的 BigDecimal。如果精度設定為 0,則不進行舍入。此方法的作用與 plus(MathContext) 方法相同。

宣告

以下是 java.math.BigDecimal.round() 方法的宣告。

public BigDecimal round(MathContext mc)

引數

mc - 要使用的上下文。

返回值

此方法返回一個根據 MathContext 設定已舍入的 BigDecimal。

異常

ArithmeticException - 如果舍入模式為 UNNECESSARY 並且 BigDecimal 運算需要進行舍入。

示例

以下示例展示了 math.BigDecimal.round() 方法的用法。

package com.tutorialspoint;

import java.math.*;

public class BigDecimalDemo {

   public static void main(String[] args) {

      // create 2 BigDecimal Objects
      BigDecimal bg1, bg2;

      bg1 = new BigDecimal("5.46497");

      MathContext mc = new MathContext(3); // 3 precision

      // bg1 is rounded using mc
      bg2 = bg1.round(mc);

      String str = "The value " + bg1 + " after rounding is " + bg2;

      // print bg2 value
      System.out.println( str );
   }
}

讓我們編譯並執行以上程式,將生成以下結果 −

The value 5.46497 after rounding is 5.46
java_math_bigdecimal.htm
廣告