BigDecimal subtract(BigDecimal subtrahend, MathContext mc)

优质
小牛编辑
121浏览
2023-12-01

描述 (Description)

java.math.BigDecimal.subtract(BigDecimal subtrahend, MathContext mc)返回一个BigDecimal,其值为(this - subtrahend),并根据上下文设置进行舍入。 如果subtrahend为零,那么在必要时将其舍入用作结果。 如果为零,则结果为subtrahend.negate(mc)。

声明 (Declaration)

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

public BigDecimal subtract(BigDecimal subtrahend, MathContext mc)

参数 (Parameters)

  • subtrahend - 要从此BigDecimal中减去的值。

  • mc - 要使用的上下文。

返回值 (Return Value)

使用减数减去后,此方法返回BigDecimal对象的值,即 - 减数,根据需要舍入。

异常 (Exception)

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

例子 (Example)

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

package cn.xnip;
import java.math.*;
public class BigDecimalDemo {
   public static void main(String[] args) {
      // create 3 BigDecimal objects
      BigDecimal bg1, bg2, bg3;
      MathContext mc = new MathContext(2); // 2 precision
      bg1 = new BigDecimal("100.123");
      bg2 = new BigDecimal("50.56");
      // subtract bg1 with bg2 using mc and assign result to bg3
      bg3 = bg1.subtract(bg2, mc);
      String str = "The Result of Subtraction is " + bg3;
      // print bg3 value
      System.out.println( str );
   }
}

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

The Result of Subtraction is 50