用2个小数位舍入Bigdecimal值 [英] Rounding Bigdecimal values with 2 Decimal Places

查看:361
本文介绍了用2个小数位舍入Bigdecimal值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个函数来转换 Bigdecimal 10.12 for 10.1234510.13 for 10.12556. 但是没有函数可以同时满足这两个转换.请帮助实现这一目标.

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.

以下是我尝试过的内容.
值为10.12345:

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)

输出:

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

值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)

输出:

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

推荐答案

我认为您要查找的RoundingModeROUND_HALF_EVEN.来自 javadoc :

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

除非两个邻居都是等距的,否则舍入模式将舍入到最近的邻居",在这种情况下,将舍入到偶数邻居.如果舍弃分数左边的数字为奇数,则表现为ROUND_HALF_UP;如果是偶数,则其行为与ROUND_HALF_DOWN相同.请注意,这是四舍五入模式,当在一系列计算中重复应用时,该模式可以最大程度地减少累积误差.

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);

正确打印:

10.12
10.13

更新:

setScale(int, int),但最终在Java 9中弃用了.您现在应该使用setScale(int, RoundingMode)例如:

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)

这篇关于用2个小数位舍入Bigdecimal值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆