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

发布于 2024-10-01 12:21:50 字数 185 浏览 3 评论 0原文

我需要以下结果

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

.round().setScale() ?我该怎么办?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

谷夏 2024-10-08 12:21:50

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

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

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

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

请注意,BigDecimal 对象是不可变的;setScaleround将返回一个新对象。)

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

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:

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

(Note that BigDecimal objects are immutable; both setScale and round will return a new object.)

疧_╮線 2024-10-08 12:21:50

如果我按照 Grodriguez 的回答,

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

这就是输出

100.23 -> 100
100.77 -> 101

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

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

这就是我得到的,

100.23 -> 100.00
100.77 -> 101.00

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

If i go by Grodriguez's answer

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.

萌梦深 2024-10-08 12:21:50

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

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

测试代码:

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

输出:

100
100
101
101

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

反目相谮 2024-10-08 12:21:50

只需查看:

http://download.oracle .com/javase/6/docs/api/java/math/BigDecimal.html#ROUND_HALF_UP

并且:

setScale(int precision, int roundingMode)

或者如果使用 Java 6,则

http://download.oracle.com/javase/6/docs/api/java/math/RoundingMode.html#HALF_UP< /a>

http://download.oracle.com/ javase/6/docs/api/java/math/MathContext.html

以及:

setScale(int precision, RoundingMode mode);
round(MathContext mc);

Simply look at:

http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#ROUND_HALF_UP

and:

setScale(int precision, int roundingMode)

Or if using Java 6, then

http://download.oracle.com/javase/6/docs/api/java/math/RoundingMode.html#HALF_UP

http://download.oracle.com/javase/6/docs/api/java/math/MathContext.html

and either:

setScale(int precision, RoundingMode mode);
round(MathContext mc);
几味少女 2024-10-08 12:21:50

我不认为你可以用一个命令来像这样舍入它。尝试

    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 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.

玩世 2024-10-08 12:21:50

如果 .round().setScale() 对您来说都不直观,您可以使用此代码舍入到任何整数步精度(例如,以 10 秒、25 秒舍入) 、50 秒、100 秒……)。

用法:

int distance = roundN(_distance, 5);

声明:

public static BigDecimal roundN(BigDecimal num, int precision){
    BigDecimal remainder = num.remainder(BigDecimal.valueOf(precision));
    System.out.println("remainder: " + remainder);

    if (remainder.compareTo(BigDecimal.valueOf((precision / 2))) < 0 ){
        System.out.println("round down");
        return num.subtract(remainder);
    } else {
        BigDecimal neg = remainder.negate().add(BigDecimal.valueOf(precision));
        System.out.println("round up");
        return num.add(neg);
    }
}

可以根据需要将尾随 .00 附加到结果中。

If neither .round() nor .setScale() seem intuitive to you, you can use this code to round to any integer steps of precision (e.g. round in 10s, 25s, 50s, 100s, ...).

Usage:

int distance = roundN(_distance, 5);

Declaration:

public static BigDecimal roundN(BigDecimal num, int precision){
    BigDecimal remainder = num.remainder(BigDecimal.valueOf(precision));
    System.out.println("remainder: " + remainder);

    if (remainder.compareTo(BigDecimal.valueOf((precision / 2))) < 0 ){
        System.out.println("round down");
        return num.subtract(remainder);
    } else {
        BigDecimal neg = remainder.negate().add(BigDecimal.valueOf(precision));
        System.out.println("round up");
        return num.add(neg);
    }
}

Trailing .00 can be appended to the result on demand.

沙沙粒小 2024-10-08 12:21:50

你想要

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

You want

round(new MathContext(0));  // or perhaps another math context with rounding mode HALF_UP
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文