Java BigDecimal:四舍五入到最接近的整数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4134047/
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:57:59  来源:igfitidea点击:

Java BigDecimal: Round to the nearest whole value

javaroundingbigdecimal

提问by n a

I need the following results

我需要以下结果

100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00

.round()or .setScale()? How do I go about this?

.round()或者.setScale()?我该怎么做?

采纳答案by Grodriguez

You can use setScale()to reduce the number of fractional digits to zero. Assuming valueholds the value to be rounded:

您可以使用setScale()将小数位数减少到零。假设value持有要四舍五入的值:

BigDecimal scaled = value.setScale(0, RoundingMode.HALF_UP);
System.out.println(value + " -> " + scaled);

Using round()is a bit more involved as it requires you to specify the number of digits to be retained. In your examples this would be 3, but this is not valid for all values:

使用round()有点复杂,因为它需要您指定要保留的位数。在您的示例中,这将是 3,但这并非对所有值都有效:

BigDecimal rounded = value.round(new MathContext(3, RoundingMode.HALF_UP));
System.out.println(value + " -> " + rounded);

(Note that BigDecimalobjects are immutable; both setScaleand roundwill return a new object.)

(请注意,BigDecimal对象是不可改变的,都setScaleround会返回一个新的对象。)

回答by Daniel Fath

I don't think you can round it like that in a single command. Try

我不认为您可以在单个命令中像这样舍入它。尝试

    ArrayList<BigDecimal> list = new ArrayList<BigDecimal>();
    list.add(new BigDecimal("100.12"));
    list.add(new BigDecimal("100.44"));
    list.add(new BigDecimal("100.50"));
    list.add(new BigDecimal("100.75"));

    for (BigDecimal bd : list){
        System.out.println(bd+" -> "+bd.setScale(0,RoundingMode.HALF_UP).setScale(2));
    }

Output:
100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00

I tested for the rest of your examples and it returns the wanted values, but I don't guarantee its correctness.

我测试了您的其余示例并返回了所需的值,但我不保证其正确性。

回答by Sean Patrick Floyd

Here's an awfully complicated solution, but it works:

这是一个非常复杂的解决方案,但它有效:

public static BigDecimal roundBigDecimal(final BigDecimal input){
    return input.round(
        new MathContext(
            input.toBigInteger().toString().length(),
            RoundingMode.HALF_UP
        )
    );
}

Test Code:

测试代码:

List<BigDecimal> bigDecimals =
    Arrays.asList(new BigDecimal("100.12"),
        new BigDecimal("100.44"),
        new BigDecimal("100.50"),
        new BigDecimal("100.75"));
for(final BigDecimal bd : bigDecimals){
    System.out.println(roundBigDecimal(bd).toPlainString());
}

Output:

输出:

100
100
101
101

100
100
101
101

回答by jacobm

You want

你要

round(new MathContext(0));  // or perhaps another math context with rounding mode HALF_UP

回答by n a

If i go by Grodriguez's answer

如果我按照 Grodriguez 的回答

System.out.println("" + value);
value = value.setScale(0, BigDecimal.ROUND_HALF_UP);
System.out.println("" + value);

This is the output

这是输出

100.23 -> 100
100.77 -> 101

Which isn't quite what i want, so i ended up doing this..

这不是我想要的,所以我最终这样做了..

System.out.println("" + value);
value = value.setScale(0, BigDecimal.ROUND_HALF_UP);
value = value.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("" + value);

This is what i get

这就是我得到的

100.23 -> 100.00
100.77 -> 101.00

This solves my problem for now .. : ) Thank you all.

这暂时解决了我的问题.. :) 谢谢大家。