Bigdecimal 根据正数取相应的负数
可以使用BigDecimal的negate()方法来取得相应的负数。negate()方法会返回当前BigDecimal对象的相反数。
以下是一个示例代码:
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal positiveNumber = new BigDecimal("10.5");
BigDecimal negativeNumber = positiveNumber.negate();
System.out.println("正数: " + positiveNumber);
System.out.println("负数: " + negativeNumber);
}
}
输出结果为:
正数: 10.5
负数: -10.5
在上面的示例中,我们先创建了一个正数BigDecimal对象positiveNumber,并使用字符串"10.5"进行初始化。然后,我们调用positiveNumber的negate()方法来获取对应的负数BigDecimal对象negativeNumber。最后,我们分别打印出正数和负数的值。
请注意,BigDecimal对象是不可变的,所以调用negate()方法后会返回一个新的BigDecimal对象,而不是修改原始对象的值
原文地址: http://www.cveoy.top/t/topic/hMpQ 著作权归作者所有。请勿转载和采集!