将BigDecimal舍入到最接近的5美分 [英] round BigDecimal to nearest 5 cents

查看:122
本文介绍了将BigDecimal舍入到最接近的5美分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图弄清楚如何将货币金额向上舍入到最接近的5美分。以下显示了我的预期结果

I'm trying to figure out how to round a monetary amount upwards to the nearest 5 cents. The following shows my expected results

1.03     => 1.05
1.051    => 1.10
1.05     => 1.05
1.900001 => 1.10

我需要结果的精度为2(如上所示)。

I need the result to be have a precision of 2 (as shown above).

按照以下建议,我能做的最好的就是这个

Following the advice below, the best I could do is this

    BigDecimal amount = new BigDecimal(990.49)

    // To round to the nearest .05, multiply by 20, round to the nearest integer, then divide by 20
   def result =  new BigDecimal(Math.ceil(amount.doubleValue() * 20) / 20)
   result.setScale(2, RoundingMode.HALF_UP)

我不相信这是100%犹太人 - 我担心转换到双打时精度可能会丢失。然而,这是我迄今为止最好的,似乎可以工作。

I'm not convinced this is 100% kosher - I'm concerned precision could be lost when converting to and from doubles. However, it's the best I've come up with so far and seems to work.

推荐答案

您可以使用普通双精度来执行此操作。

You can use plain double to do this.

double amount = 990.49;
double rounded = ((double) (long) (amount * 20 + 0.5)) / 20;

编辑:对于负数,您需要减去0.5

for negative numbers you need to subtract 0.5

这篇关于将BigDecimal舍入到最接近的5美分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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