In Java, BigDecimal rounds to two decimal places.

In Java, the BigDecimal class can be used for precise numerical calculations and allows setting the number of decimal places to be retained. Below is an example code demonstrating how to use BigDecimal to keep two decimal places:

import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        // 创建一个BigDecimal对象,传入需要保留两位小数的数值
        BigDecimal number = new BigDecimal("3.1415926");

        // 使用setScale方法设置保留小数的位数,第一个参数为保留的小数位数,第二个参数为舍入模式
        // RoundingMode.HALF_UP表示四舍五入
        BigDecimal result = number.setScale(2, BigDecimal.ROUND_HALF_UP);

        // 打印结果
        System.out.println(result);  // 输出结果为3.14
    }
}

In the example above, we used the setScale method of BigDecimal to set the number of decimal places to 2 and used the round half up rounding mode. Finally, we printed the result as 3.14.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds