Rounding BigDecimal to *always* have two decimal places

不羁岁月 提交于 2019-11-26 04:38:29

问题


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

I\'m using

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.73
rounded 0.819 to 0.82

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?


回答1:


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


来源:https://stackoverflow.com/questions/15643280/rounding-bigdecimal-to-always-have-two-decimal-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!