用java从大到小输入两个小数,用2个小数位舍入Bigdecimal值

I want a function to convert Bigdecimal 10.12 for 10.12345 and 10.13 for 10.12556.

But no function is satisfying both conversion in same time.Please help to achieve this.

Below is what I tried.

With value 10.12345:

BigDecimal a = new BigDecimal("10.12345");

a.setScale(2, BigDecimal.ROUND_UP)

a.setScale(2, BigDecimal.ROUND_CEILING)

a.setScale(2, BigDecimal.ROUND_DOWN)

a.setScale(2, BigDecimal.ROUND_FLOOR)

a.setScale(2, BigDecimal.ROUND_HALF_DOWN)

a.setScale(2, BigDecimal.ROUND_HALF_EVEN)

a.setScale(2, BigDecimal.ROUND_HALF_UP)

Output :

10.12345::10.13

10.12345::10.13

10.12345::10.12

10.12345::10.12

10.12345::10.12

10.12345::10.12

10.12345::10.12

With value 10.12556:

BigDecimal b = new BigDecimal("10.12556");

b.setScale(2, BigDecimal.ROUND_UP)

b.setScale(2, BigDecimal.ROUND_CEILING)

b.setScale(2, BigDecimal.ROUND_DOWN)

b.setScale(2, BigDecimal.ROUND_FLOOR)

b.setScale(2, BigDecimal.ROUND_HALF_DOWN)

b.setScale(2, BigDecimal.ROUND_HALF_EVEN)

b.setScale(2, BigDecimal.ROUND_HALF_UP)

Output :

10.12556::10.13

10.12556::10.13

10.12556::10.12

10.12556::10.12

10.12556::10.12

10.12556::10.12

10.12556::10.12

解决方案

I think that the RoundingMode you are looking for is ROUND_HALF_EVEN. From the javadoc:

Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations.

Here is a quick test case:

BigDecimal a = new BigDecimal("10.12345");

BigDecimal b = new BigDecimal("10.12556");

a = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);

b = b.setScale(2, BigDecimal.ROUND_HALF_EVEN);

System.out.println(a);

System.out.println(b);

Correctly prints:

10.12

10.13

UPDATE:

setScale(int, int) has not been recommended since Java 1.5, when enums were first introduced, and was finally deprecated in Java 9. You should now use setScale(int, RoundingMode) e.g:

setScale(2, RoundingMode.HALF_EVEN)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值