Search code examples
javamathenumsroundingbigdecimal

Rounding mode from java Math package for .555 not works


How about my problem is the following, I am using the rounding mode to round and truncate some quantities but none of the enumerations works for the business rule that my client needs, I give as an example the following:

new BigDecimal(5.551).setScale(2, RoundingMode.[ENUM]) <-- DEberia regresar 5.55 OK
new BigDecimal(5.554).setScale(2, RoundingMode.[ENUM]) <-- DEberia regresar 5.55 OK
new BigDecimal(5.555).setScale(2, RoundingMode.[ENUM]) <-- DEberia regresar 5.55 It should be 5.56 
new BigDecimal(5.559).setScale(2, RoundingMode.[ENUM]) <-- DEberia regresar 5.56 OK

I had used HALF_DOWN which was the closest one but I came across this case in which I have pure fives and so it didn't work anymore.


Solution

  • Do it as follows:

    import java.math.BigDecimal;
    import java.math.RoundingMode;
    
    public class Main {
        public static void main(String[] args) {
    
            System.out.println(new BigDecimal(String.valueOf(5.551)).setScale(2, RoundingMode.HALF_UP));
            System.out.println(new BigDecimal(String.valueOf(5.554)).setScale(2, RoundingMode.HALF_UP));
            System.out.println(new BigDecimal(String.valueOf(5.555)).setScale(2, RoundingMode.HALF_UP));
            System.out.println(new BigDecimal(String.valueOf(5.559)).setScale(2, RoundingMode.HALF_UP));
        }
    }
    

    Output:

    5.55
    5.55
    5.56
    5.56