Recently I hat to implement a function that would round to the nearest 5 cents and after googling around a bit I found bits and pieces here and there but none just worked for me, so below you can find a function that should do just that
/** * Rounds a decimal number to the nearest 5 cents using the following rules * * Rounding rules : * - 0.1299 = 0.10 * - 0.1300 = 0.15 * - 0.1799 = 0.15 * - 0.1800 = 0.20 * * @param value the BigDecimal value to round * @return the rounded value for the big decimal with a scale of 2 */ public static BigDecimal roundToNearest5Cents(final BigDecimal value) { return value.setScale(2, RoundingMode.FLOOR).multiply(new BigDecimal(20)).add(new BigDecimal("0.5")) .setScale(0, RoundingMode.FLOOR).divide(new BigDecimal(20)).setScale(2, RoundingMode.FLOOR); }
No comments:
Post a Comment