views:

165

answers:

3

Hi,

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

A: 

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

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

oedo
`Math` takes `float` or `double` arguments, not `BigDecimal`.
Péter Török
thanks for pointing that out, peter. answer fixed.
oedo
Why do you multiply by 4?
because if you multiply by 4, then round the number, then divide by 4, then you get a number that's rounded to the nearest 1/4.
oedo
+1  A: 

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.

Andrzej Doyle
The code is actually very demanding... it runs more than 1000000 times in hour
+2  A: 

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