Java BigDecimal add()方法及示例
java.math.BigDecimal .add(BigDecimal val)是用来计算两个BigDecimals的算术和。该方法用于对范围远大于Java最大数据类型double范围的大数进行算术相加,而不影响结果的精度。该方法对当前的BigDecimal进行运算,该方法被调用时,BigDecimal作为参数被传递。
在Java中,有两个重载的add方法,如下所示。
- add(BigDecimal val)
- add (BigDecimal val, MathContext mc)
add(BigDecimal val)
语法
public BigDecimal add(BigDecimal val)
参数。本方法接受一个参数val,它是要添加到这个BigDecimal中的值。
返回值。该方法返回一个BigDecimal,该BigDecimal持有sum (this + val),其比例为max(this. scale() , val. scale() )。
下面的程序是用来说明BigDecimal的add()方法。
// Java program to demonstrate
// add() method of BigDecimal
import java.math.BigDecimal;
public class GFG {
public static void main(String[] args)
{
// BigDecimal object to store the result
BigDecimal sum;
// For user input
// Use Scanner or BufferedReader
// Two objects of String created
// Holds the values to calculate the sum
String input1
= "545456468445645468464645";
String input2
= "4256456484464684864864";
// Convert the string input to BigDecimal
BigDecimal a
= new BigDecimal(input1);
BigDecimal b
= new BigDecimal(input2);
// Using add() method
sum = a.add(b);
// Display the result in BigDecimal
System.out.println("The sum of\n"
+ a + " \nand\n" + b + " "
+ "\nis\n" + sum + "\n");
}
}
输出。
The sum of
545456468445645468464645
and
4256456484464684864864
is
549712924930110153329509
add(BigDecimal val, MathContext mc)
语法
public BigDecimal add(BigDecimal val, MathContext mc)
参数。本方法接受两个参数,一个是val,即要添加到BigDecimal中的值,一个是MathContext类型的mc。
返回值。该方法返回一个BigDecimal,其中包含总和(this + val),并根据上下文设置进行四舍五入。如果其中一个数字是零,并且精度设置为非零,那么另一个数字将被用作结果,必要时进行四舍五入。
下面的程序是用来说明BigDecimal的add()方法。
// Java program to demonstrate
// add() method of BigDecimal
import java.math.*;
public class GFG {
public static void main(String[] args)
{
// BigDecimal object to store the result
BigDecimal sum;
// For user input
// Use Scanner or BufferedReader
// Two objects of String created
// Holds the values to calculate the sum
String input1
= "9854228445645468464645";
String input2
= "4252145764464684864864";
// Convert the string input to BigDecimal
BigDecimal a
= new BigDecimal(input1);
BigDecimal b
= new BigDecimal(input2);
// Set precision to 10
MathContext mc
= new MathContext(10);
// Using add() method
sum = a.add(b, mc);
// Display the result in BigDecimal
System.out.println("The sum of\n"
+ a + " \nand\n" + b + " "
+ "\nis\n" + sum + "\n");
}
}
输出。
The sum of
9854228445645468464645
and
4252145764464684864864
is
1.410637421E+22
**参考文献: ** https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#add(java.math.BigDecimal)