Java中BigDecimal怎样取反

在Java中,要对BigDecimal对象进行取反操作,可以使用 negate()方法。这方法将返回一个新的BigDecimal对象,其值为原始BigDecimal对象的相反数。

示例代码:

import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        BigDecimal number = new BigDecimal("10.5");

        // 取反操作
        BigDecimal negated = number.negate();

        System.out.println("原始值: " + number);
        System.out.println("取反后的值: " + negated);
    }
}
 
 

在上述示例中,number.negate()会将BigDecimal对象 number的值取反,并将结果存储在新的BigDecimal对象 negated中。

posted @ 2025-03-14 16:15  tg109_wow  阅读(230)  评论(0)    收藏  举报