當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Java.math.BigDecimal.subtract()用法及代碼示例


描述

這個java.math.BigDecimal.subtract(BigDecimal subtrahend, MathContext mc)返回一個 BigDecimal,其值為 (this - subtrahend),並根據上下文設置進行舍入。如果被減數為零,則將其用作結果,必要時進行四舍五入。如果這是零,則結果為 subtrahend.negate(mc)。

聲明

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

public BigDecimal subtract(BigDecimal subtrahend, MathContext mc)

參數

  • subtrahend- 要從此 BigDecimal 中減去的值。

  • mc- 要使用的上下文。

返回值

此方法返回 BigDecimal 對象與減數相減後的值,即 this - subtrahend,根據需要進行四舍五入。

異常

ArithmeticException− 如果結果不準確但舍入模式為 UNNECESSARY

示例

下麵的例子展示了 math.BigDecimal.subtract() 方法的用法。

package com.tutorialspoint;

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

相關用法


注:本文由純淨天空篩選整理自 Java.math.BigDecimal.subtract() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。