BigDecimal类的negate()方法 (BigDecimal Class negate() method)
Syntax:
句法:
public BigDecimal negate();
public BigDecimal negate(MathContext ma_co);
negate() method is available in java.math package.
negate()方法在java.math包中可用。
negate() method is used to get a negation of this BigDecimal and its scale is non-negative.
negate()方法用于获取此BigDecimal的取反,并且其标度为非负数。
negate(MathContext ma_co) method is used to retrieve a negation of this BigDecimal along with rounding based on the given MathContext settings.
negate(MathContext ma_co)方法用于检索此BigDecimal的取反以及基于给定MathContext设置的舍入。
These methods may throw an exception at the time of the negation of an object.
这些方法在对象取反时可能会引发异常。
ArithmeticException: This exception may throw when the result is not accurate and set the rounding mode "UNNECESSARY".
ArithmeticException :当结果不正确并且将舍入模式设置为“ UNNECESSARY”时,可能会引发此异常。
These are non-static methods and it is accessible with class objects and if we try to access these methods with the class name then we will get an error.
这些是非静态方法,可通过类对象访问,如果尝试使用类名访问这些方法,则会收到错误消息。
Parameter(s):
参数:
In the first case, negate(),
在第一种情况下, negate() ,
- It does not accept any parameter.
In the first case, negate(MathContext ma_co),
在第一种情况下, negate(MathContext ma_co) ,
- MathContext ma_co – represents the context setting to use in rounding.
- MathContext ma_co –表示要舍入的上下文设置。
Return value:
返回值:
In both the cases, the return type of the method is BigDecimal,
在这两种情况下,方法的返回类型均为BigDecimal 。
In the first case, it returns the negation of this BigDecimal.
在第一种情况下,它返回此BigDecimal的取反。
In the second case, it returns the negation of this BigDecimal. with rounding if required.
在第二种情况下,它返回此BigDecimal的取反。 如果需要,请四舍五入。
Example:
例:
// Java program to demonstrate the example
// of negate() method of BigDecimal
import java.math.*;
public class NegateOfBD {
public static void main(String args[]) {
// Initialize two variables val1,
// val2
String val1 = "-10.30";
int val2 = 4;
// Initialize two BigDecimal objects and
// one MathContext
BigDecimal b_dec1 = new BigDecimal(val1);
BigDecimal b_dec2 = new BigDecimal(val2);
MathContext ma_co = new MathContext(2, RoundingMode.CEILING);
System.out.println("negate(): ");
// returns the negate value of this BigDecimal
// like (-b_dec2)
BigDecimal negate = b_dec2.negate();
System.out.println("b_dec2.negate(): " + negate);
System.out.println(" ");
System.out.println("negate(MathContext): ");
// returns the negate value of this BigDecimal
// (-b_dec1) and return the result based on the given
// context settings
negate = b_dec1.negate(ma_co);
System.out.println("b_dec1.negate(ma_co): " + negate);
}
}
Output
输出量
negate():
b_dec2.negate(): -4negate(MathContext):
b_dec1.negate(ma_co): 11
翻译自: https://www.includehelp.com/java/bigdecimal-negate-method-with-example.aspx