Java.math.BigDecimal.subtract() Method

Advertisements


Description

The java.math.BigDecimal.subtract(BigDecimal subtrahend, MathContext mc) returns a BigDecimal whose value is (this - subtrahend), with rounding according to the context settings. If subtrahend is zero then this, rounded if necessary, is used as the result. If this is zero then the result is subtrahend.negate(mc).

Declaration

Following is the declaration for java.math.BigDecimal.subtract() method

public BigDecimal subtract(BigDecimal subtrahend, MathContext mc)

Parameters

  • subtrahend - value to be subtracted from this BigDecimal

  • mc - the context to use

Return Value

This method returns the value of BigDecimal object after subtraction with the subtrahend i.e this - subtrahend, rounded as necessary.

Exception

  • ArithmeticException - if the result is inexact but the rounding mode is UNNECESSARY

Example

The following example shows the usage of math.BigDecimal.subtract() method

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 );
    }
}

Let us compile and run the above program, this will produce the following result:

The Result of Subtraction is 50



Advertisements
Advertisements