Search code examples
javaroundingbigdecimal

BigDecimal rounding question


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


Solution

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