将 BigDecimal 舍入到*总是*​​有两个小数位 [英] Rounding BigDecimal to *always* have two decimal places

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

问题描述

我正在尝试将 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 舍入到*总是*​​有两个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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