Java.math.BigDecimal.add()方法



说明

java.math.BigDecimal.add(BigDecimal augend, MathContext mc) 返回值为 (this + augend),根据 MathContext 设置进行舍入。如果其中一个数字为零且精度设置不为零,则另一个数字(必要时会舍入)将用作结果。

声明

以下是 java.math.BigDecimal.add() 方法的声明。

public BigDecimal add(BigDecimal augend, MathContext mc)

参数

  • augend − 要添加到此 BigDecimal 的值。

  • mc − 要使用的上下文。

返回值

此方法返回一个 BigDecimal 对象,其值为 this + augend,必要时进行舍入

异常

ArithmeticException − 如果结果不准确但舍入模式为 UNNECESSARY。

示例

以下示例显示了 math.BigDecimal.add() 方法的用法。

package com.tutorialspoint;

import java.math.*;

public class BigDecimalDemo {

   public static void main(String[] args) {

      // create 3 BigDecimal objects
      BigDecimal bg1,bg2,bg3,bg4;

      // assign value to bg1 and bg2
      bg1 = new BigDecimal("40.732");
      bg2 = new BigDecimal("30.12");

      // print bg1 and bg2 value
      System.out.println("Object Value is " + bg1);
      System.out.println("Augend value is " + bg2);

      // create MathContext object with 4 precision
      MathContext mc = new MathContext(4);

      // perform add operation on bg1 with augend bg2 and context mc
      bg3 = bg1.add(bg2,mc);

      // print bg3 value with
      System.out.println("Result is " + bg3);
   }
}

让我们编译并运行上述程序,这将产生以下结果 −

Object Value is 40.732
Augend value is 30.12
Result is 70.85
java_math_bigdecimal.htm
广告
© . All rights reserved.