Java BigDecimal: Keep Integer Part

In Java, you can use the setScale() method to retain the integer part. Here is how you can do it:

import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        BigDecimal number = new BigDecimal("123.456");
        
        // 保留整数部分
        BigDecimal result = number.setScale(0, BigDecimal.ROUND_DOWN);
        
        System.out.println("保留整数部分后的结果:" + result);
    }
}

In the example above, we start by creating a BigDecimal object ‘number’, then use the setScale() method to set the number of decimal places to 0 and specify the rounding mode as BigDecimal.ROUND_DOWN to retain the integer part. Finally, we print the result after preserving the integer part.

In the setScale() method, the first parameter indicates the number of decimal places to preserve, while the second parameter represents the rounding mode, where BigDecimal.ROUND_DOWN signifies rounding down. Adjusting the first parameter allows for different integer parts to be preserved.

bannerAds