Blog Post: BigDecimal rounding to the nearest 5 cents with Java’s BigDecimal

Blog Post: BigDecimal rounding to the nearest 5 cents with Java’s BigDecimal

This post was originally published on this site

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


Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.