How to set specific precision to BigDecimal in Java?

亡梦爱人 提交于 2020-12-16 03:52:45

问题


I have BigDecimal value.

BigDecimal price = new BigDecimal("100500100500.9999999").setScale(2, BigDecimal.ROUND_HALF_EVEN);

It prints 100500100501.00, although I need 100500100500.99. Is it possible to make some restriction to precision evaluating?


回答1:


You can use the rounding mode constant ROUND_DOWN in setScale. However, the overloaded setScale method that takes a RoudingMode is preferred.

BigDecimal price = new BigDecimal("100500100500.9999999")
    .setScale(2, RoundingMode.DOWN);

Output:

100500100500.99


来源:https://stackoverflow.com/questions/26069522/how-to-set-specific-precision-to-bigdecimal-in-java

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