Java中BigDecimal算出来的结果不对?-灵析社区

我想对你说

这段代码为什么输出的872? public static void main(String[] args) { BigDecimal currentInventoryNumber = BigDecimal.valueOf(872.000); BigDecimal convertedNumber = BigDecimal.valueOf(0.200); System.out.println(currentInventoryNumber.subtract(convertedNumber, new MathContext(3))); }

阅读量:200

点赞量:15

问AI
第二个参数new MathContext(3)表示精度为小数点后三位。 因为currentInventoryNumber的值为872.000,而convertedNumber的值为0.200,所以它们的差值为871.800。使用了MathContext(3)会将结果四舍五入到小数点后三位,也就是872.000。 "image.png" (https://wmprod.oss-cn-shanghai.aliyuncs.com/images/20241226/183cfe58345a4f9f36d5f2680721a72a.png) "image.png" (https://wmprod.oss-cn-shanghai.aliyuncs.com/images/20241226/003bcc68f32cb78718ca181f07d167d1.png)