如何在Java中将特定精度设置为BigDecimal? [英] How to set specific precision to BigDecimal in Java?

查看:82
本文介绍了如何在Java中将特定精度设置为BigDecimal?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有BigDecimal值.

I have BigDecimal value.

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

它打印 100500100501.00 ,尽管我需要 100500100500.99 .可以对精度评估施加一些限制吗?

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

推荐答案

您可以在 setScale 中使用舍入模式常量 ROUND_DOWN .但是,首选采用 RoudingMode 的重载 setScale 方法.

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);

输出:

100500100500.99

这篇关于如何在Java中将特定精度设置为BigDecimal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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