将BigDecimal舍入为* always *有两位小数 [英] Rounding BigDecimal to *always* have two decimal places

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

问题描述

我正在尝试将BigDecimal值向上舍入到小数点后两位。

I'm trying to round BigDecimal values up, to two decimal places.

我正在使用

BigDecimal rounded = value.round(new MathContext(2, RoundingMode.CEILING));
logger.trace("rounded {} to {}", value, rounded);

但它不能始终如一地执行:

but it doesn't do what I want consistently:

rounded 0.819 to 0.82
rounded 1.092 to 1.1
rounded 1.365 to 1.4 // should be 1.37
rounded 2.730 to 2.8 // should be 2.74
rounded 0.819 to 0.82

我不关心有效数字,我只是想要两位小数。我如何使用BigDecimal执行此操作?或者是否有另一个类/库更适合这个?

I don't care about significant digits, I just want two decimal places. How do I do this with BigDecimal? Or is there another class/library better suited to this?

推荐答案

value = value.setScale(2, RoundingMode.CEILING)

这篇关于将BigDecimal舍入为* always *有两位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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