BigDecimal四舍五入问题

发布于 2024-09-02 13:06:23 字数 225 浏览 2 评论 0 原文

我希望能够将任何数字四舍五入到整数的四分之一。

例如:

100.33 -> 100.50
100.12 -> 100.25
100.66 -> 100.75
100.99 -> 101.00
100.70 -> 100.75
100.00 -> 100.00
100.25 -> 100.25

等等...

谢谢大家...

I would like to be able to round up any number to quater of the whole number.

For example:

100.33 -> 100.50
100.12 -> 100.25
100.66 -> 100.75
100.99 -> 101.00
100.70 -> 100.75
100.00 -> 100.00
100.25 -> 100.25

etc...

thank guys...

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

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

发布评论

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

评论(3

余厌 2024-09-09 13:06:23

这会满足您的需要:乘以 4,向上舍入,然后除以 4。

    String[] tests = {
        "100.33", "100.12", "100.66", "100.99", "100.70", "100.00", "100.25",
    };
    final BigDecimal FOUR = BigDecimal.valueOf(4);
    for (String test : tests) {
        BigDecimal d = new BigDecimal(test);
        d = d.multiply(FOUR).setScale(0, RoundingMode.UP)
             .divide(FOUR, 2, RoundingMode.UNNECESSARY);
        System.out.println(d);
    }

This does what you need: it multiplies by 4, rounds up, then divides back by 4.

    String[] tests = {
        "100.33", "100.12", "100.66", "100.99", "100.70", "100.00", "100.25",
    };
    final BigDecimal FOUR = BigDecimal.valueOf(4);
    for (String test : tests) {
        BigDecimal d = new BigDecimal(test);
        d = d.multiply(FOUR).setScale(0, RoundingMode.UP)
             .divide(FOUR, 2, RoundingMode.UNNECESSARY);
        System.out.println(d);
    }
半窗疏影 2024-09-09 13:06:23

我认为如果没有一些手动干预这是不可能的。您可以通过传入 MathContext 到 BigDecimal 构造函数;但是,该类的对象中使用的舍入模式必须是 RoundingMode 枚举常量(并且这些都没有实现您想要的舍入类型)。如果这是一个您可以编写自己的定义的接口,那就太好了,但您已经有了它。

根据代码所需的性能,您当然可以将数字乘以 4,四舍五入到最接近的整数,然后再次除以 4。这可能是最少的实际编程工作,并且相对容易理解,因此如果您的代码不在性能关键部分,这就是我的建议。

I don't believe this is possible without some manual intervention. You get to specify the rounding settings by passing in a MathContext to the BigDecimal constructor; however, the rounding mode used in an object of that class has to be a RoundingMode enum constant (and none of those implement the kind of rounding you want). It would be nice if this was instead an interface that you could write your own definition of, but there you have it.

Depending on how performant your code needs to be, you could of course multiply the number by 4, round up to the nearest whole number, and divide by 4 again. This is probably the least actual programming effort and is relatively easily understandable, so if your code isn't in a performance-critical section it's what I'd suggest.

无人接听 2024-09-09 13:06:23

Math.round(x.doubleValue() * 4) / 4

Math.ceilMath.floor 取决于你想要的

Math.round(x.doubleValue() * 4) / 4

or Math.ceil or Math.floor depending on what you want

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文