Java中BigDecimal的数学运算
让我们使用Java中的内置方法在BigDecimal上应用以下操作-
Addition: add() method Subtraction: subtract() method Multiplication: multiply() method Division: divide() method
让我们创建三个BigInteger对象-
BigDecimal val1 = new BigDecimal("37578975587.876876989"); BigDecimal val2 = new BigDecimal("62567875598.976876569"); BigDecimal val3 = new BigDecimal("72567875598.376876569");
对它们应用数学运算-
val1 = val1.add(val2); System.out.println("Addition Operation = " + val1); val1 = val1.multiply(val2); System.out.println("Multiplication Operation = " + val1); val2 = val3.subtract(val2); System.out.println("Subtract Operation = " + val2);
以下是一个例子-
示例
import java.math.BigDecimal; public class Demo { public static void main(String[] argv) throws Exception { BigDecimal val1 = new BigDecimal("37578975587.876876989"); BigDecimal val2 = new BigDecimal("62567875598.976876569"); BigDecimal val3 = new BigDecimal("72567875598.376876569"); System.out.println("Value 1 : "+val1); System.out.println("Value 2 : "+val2); val1 = val1.add(val2); System.out.println("Addition Operation = " + val1); val1 = val1.multiply(val2); System.out.println("Multiplication Operation = " + val1); val2 = val3.subtract(val2); System.out.println("Subtract Operation = " + val2); val2 = val3.divide(val2,BigDecimal.ROUND_UP); System.out.println("Division Operation = " + val2); } }
输出结果
Value 1 : 37578975587.876876989 Value 2 : 62567875598.976876569 Addition Operation = 100146851186.853753558 Multiplication Operation = 6265975726688315418019.861150364510582502 Subtract Operation = 9999999999.400000000 Division Operation = 7.256787561