Search code examples
javaroundingbigdecimal

Strange rounding issue with BigDecimal


Note this is not a duplicate, I'm and referring to rounding; not adding.

So I am dealing with BigDecimal and everything I do works as planned except for the rounding of certain numbers. It is easier to explain with code, but the rounding changes property between numbers. Note this is a always round down mode (truncating). It should round to 6 numbers in the decimal point.

    System.out.println( (new BigDecimal(1.340)).round(new MathContext(7, RoundingMode.DOWN))); //returns 1.400000
    System.out.println( (new BigDecimal(2.340)).round(new MathContext(7, RoundingMode.DOWN))); //returns 2.339999

I understand BigDecimal, rounding, etc. What is strange is simply changing the first number from 1 to 2, 3, 4, 5, ... n makes the value n.339999. In other words, for n.340 where n > 1, rounding in this form gives n.339999 while if n = 1, it yields, 1.400000

What am I doing wrong? How can I fix this problem and make it the 1.400000 version? It is preferable to use this format because everything else I am dealing with (unnecessary to this question) works in this format where it is rounded in this way.


Solution

  • Don't initialize your BigDecimal with a double. You already have a precision problem when you create your BigDecimal. Use a String instead:

    System.out.println( (new BigDecimal("1.340")).round(new MathContext(7, RoundingMode.DOWN))); //returns 1.340
    System.out.println( (new BigDecimal("2.340")).round(new MathContext(7, RoundingMode.DOWN))); //returns 2.340