问题描述
我们正在将一些sybase代码替换为Java,并且对Rounding BigDecimal出现问题以匹配sybase返回的内容
We are replacing some sybase code to Java and having issue with Rounding BigDecimal to match what sybase returns
11.4443999999999999062083588796667754650115966796875-应该返回11.44
11.4443999999999999062083588796667754650115966796875 - Should return 11.44
和
35.9549999999999982946974341757595539093017578125-应该返回35.96
35.9549999999999982946974341757595539093017578125 - should return 35.96
我尝试了将比例设置为2的所有不同的舍入选项,但是没有一个都适用.最好的选择是什么?
I have tried all different rounding options with scale set to 2, but none works for both. What is the best option?
推荐答案
您将必须采取两步方法.首先使用RoundingMode.HALF_UP
将比例缩放为3,然后将比例缩放为2:
You'll have to take a two-step approach. First round to scale 3, then to scale 2, using RoundingMode.HALF_UP
:
BigDecimal value1 = new BigDecimal("11.4443999999999999062083588796667754650115966796875");
BigDecimal value2 = new BigDecimal("35.9549999999999982946974341757595539093017578125");
BigDecimal rounded1 = value1.setScale(3, RoundingMode.HALF_UP); // 11.444
rounded1 = rounded1.setScale(2, RoundingMode.HALF_UP); // 11.44
BigDecimal rounded2 = value2.setScale(3, RoundingMode.HALF_UP); // 35.955
rounded2 = rounded2.setScale(2, RoundingMode.HALF_UP); // 35.96
这篇关于BigDecimal舍入模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!