- Java.math 包详解
- Java.math - 枚举
- Java.math - 讨论
Java.math.BigDecimal.subtract() 方法
描述
java.math.BigDecimal.subtract(BigDecimal subtrahend, MathContext mc) 返回的值为 (this - subtrahend),根据上下文设置进行舍入。如果 subtrahend 为零,则使用 this(如果需要,已经舍入)作为结果。如果 this 为零,则结果为 subtrahend.negate(mc)。
声明
以下是 java.math.BigDecimal.subtract() 方法的声明。
public BigDecimal subtract(BigDecimal subtrahend, MathContext mc)
参数
subtrahend − 从此 BigDecimal 减去的数值。
mc − 要使用的上下文。
返回值
此方法返回 BigDecimal 对象在减去 subtrahend(即 this - subtrahend)之后的值,根据需要进行舍入。
异常
算术异常 − 如果结果不精确,但舍入模式为 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.htm
广告