BigDecimal subtract() Method in Java with Examples
Last Updated :
27 May, 2019
The java.math.BigDecimal.subtract(BigDecimal val) is used to calculate the Arithmetic difference of two BigDecimals. This method is used to find the arithmetic difference of large numbers without compromising with the precision of the result. This method performs an operation upon the current BigDecimal by which this method is called and BigDecimal passed as the parameter.
There are two overloads of subtract method available in java which are listed below:
- subtract(BigDecimal val)
- subtract(BigDecimal val, MathContext mc)
subtract(BigDecimal val)
Syntax:
public BigDecimal subtract(BigDecimal val)
Parameters: This method accepts a parameter val which is the value to be subtracted from this BigDecimal.
Return value: This method returns a BigDecimal which holds difference (this – val), and whose scale is max(this.scale(), val.scale()).
Below programs is used to illustrate the subtract() method of BigDecimal.
import java.math.BigDecimal;
public class GFG {
public static void main(String[] args)
{
BigDecimal diff;
String input1
= "545456468445645468464645" ;
String input2
= "425645648446468486486452" ;
BigDecimal a
= new BigDecimal(input1);
BigDecimal b
= new BigDecimal(input2);
diff = a.subtract(b);
System.out.println( "The difference of\n"
+ a + " \nand\n" + b + " "
+ "\nis\n" + diff + "\n" );
}
}
|
Output:
The difference of
545456468445645468464645
and
425645648446468486486452
is
119810819999176981978193
subtract(BigDecimal val, MathContext mc)
Syntax:
public BigDecimal subtract(BigDecimal val, MathContext mc)
Parameters: This method accepts two parameter, one is val which is the value to be subtracted from this BigDecimal and a mc of type MathContext.
Return value: This method returns a BigDecimal which holds difference (this – val), with rounding according to the context settings.
Below programs is used to illustrate the subtract() method of BigDecimal.
import java.math.*;
public class GFG {
public static void main(String[] args)
{
BigDecimal diff;
String input1
= "468445645468464645" ;
String input2
= "4256456484464684864864" ;
BigDecimal a
= new BigDecimal(input1);
BigDecimal b
= new BigDecimal(input2);
MathContext mc
= new MathContext( 10 );
diff = a.subtract(b, mc);
System.out.println( "The difference of\n"
+ a + " \nand\n" + b + " "
+ "\nis\n" + diff + "\n" );
}
}
|
Output:
The difference of
468445645468464645
and
4256456484464684864864
is
-4.255988039E+21
References: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#subtract(java.math.BigDecimal)
Share your thoughts in the comments
Please Login to comment...