Java – Rounding a Java BigDecimal to the nearest interval

bigdecimalintervalsjavarounding

I have a BigDecimal calculation result which I need to round to the nearest specified interval (in this case it's the financial market tick size).

e.g. Price [Tick Size] -> Rounded Price

100.1 [0.25] -> 100
100.2 [0.25] -> 100.25
100.1 [0.125] -> 100.125
100.2 [0.125] -> 100.25

Thanks.

Update: schnaader's solution, translated into Java/BigDecimal terms:

price = price.divide(tick).setScale(0, RoundingMode.HALF_UP).multiply(tick)

Best Answer

You could normalize tick size and then use the usual rounding methods:

100.1 [0.25] -> * (1/0.25) -> 400.4 [1]  -> round -> 400 -> / (1/0.25) -> 100
100.2 [0.25] -> * (1/0.25) -> 400.8 [1] -> round -> 401 -> / (1/0.25) -> 100.25

So it should be:

Price = Round(Price / Tick) * Tick;

Also note that you seem to have to set the correct rounding mode for BigDecimals. See BigDecimal Docs for example. So you should be sure to set this correct and write some tests to check the correctness of your code.