Java 如何在不舍入的情况下截断 BigDecimal

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24272849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:14:05  来源:igfitidea点击:

How to truncate a BigDecimal without rounding

javaroundingbigdecimalarithmeticexception

提问by JJ180

After a series of calculations in my code, I have a BigDecimalwith value 0.01954

在我的代码中经过一系列计算后,我有了一个BigDecimal0.01954

I then need to multiply this BigDecimalby 100and I wish the calculated value to be 1.95

那么我就需要这个相乘BigDecimal100,我希望计算出的值是1.95

I do not wish to perform any rounding up or down, I just want any values beyond two decimal places to be truncated

我不想执行任何向上或向下舍入,我只想截断小数点后两位以上的任何值

I tried setting scale to 2, but then I got an ArithmeticExceptionsaying rounding is necessary. How can I set scale without specifying rounding?

我尝试将比例设置为 2,但后来我得到了一个ArithmeticException说法,四舍五入是必要的。如何在不指定舍入的情况下设置比例?

采纳答案by GriffeyDog

Use either RoundingMode.DOWNor RoundingMode.FLOOR.

使用RoundingMode.DOWNRoundingMode.FLOOR

BigDecimal newValue = myBigDecimal.setScale(2, RoundingMode.DOWN);

回答by user1676075

Use the setScale override that includes RoundingMode:

使用包含 RoundingMode 的 setScale 覆盖:

value.setScale(2, RoundingMode.DOWN);