要使用MathContext保留四位小数,可以使用以下代码:

import java.math.BigDecimal;
import java.math.MathContext;

public class Main {
    public static void main(String[] args) {
        BigDecimal number = new BigDecimal('3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679');
        MathContext mathContext = new MathContext(4);
        BigDecimal roundedNumber = number.round(mathContext);
        System.out.println(roundedNumber);
    }
}

在上面的代码中,我们创建了一个BigDecimal对象number,它包含了一个很长的数字。然后,我们创建了一个MathContext对象mathContext,指定保留四位小数。

使用round()方法和mathContext对象对number进行四舍五入,并将结果存储在roundedNumber中。最后,我们打印出roundedNumber。

这将输出:3.142

Java BigDecimal保留四位小数:使用MathContext

原文地址: http://www.cveoy.top/t/topic/envo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录