0

Why I'm getting following output:

1.11

1.13

when run below code:

public static void main(String[] args) {

    double aDouble = 1.115;
    double bDouble = 1.125;

    System.out.println(roundTo2Decimal(aDouble));
    System.out.println(roundTo2Decimal(bDouble));
}

public static BigDecimal roundTo2Decimal(double doubleToRound){
    BigDecimal bigDecimal = new BigDecimal(doubleToRound);
    return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
}

instead of expected result:

1.12

1.13 ?

hqmr
  • 13
  • 3

3 Answers3

2

This occurs due to precision loss when representing 1.115 as double:

1.115 = 1.114999999999999991118215803E0
1.125 = 1.125E0
Sergei Rodionov
  • 4,079
  • 6
  • 27
  • 44
1

Pretty sure this is just standard floating point imprecision. 0.125 = 1/8 which is exactly expressible in binary. 0.115 isn't so it's not stored exactly, and, apparently, is stored as something that rounds away from what you expect. Try System.out.println the double itself.

djechlin
  • 59,258
  • 35
  • 162
  • 290
  • Thanks. I found some info about fp inaccuracy: http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples – hqmr Mar 29 '16 at 20:05
0
<code>
//to achieve what u need change your method to
    public static BigDecimal roundTo2Decimal(double doubleToRound) {
        BigDecimal bigDecimal = new BigDecimal(doubleToRound);
        return bigDecimal.setScale(2, RoundingMode.CEILING);
    }

</code>
Gaurav
  • 126
  • 7
  • Although this may provide the author with the desired results, it does not answer the question that was asked and should probably be a comment instead - such as: "*Instead of `BigDecimal.ROUND_HALF_UP`, use `RoundingMode.CEILING`*". – OhBeWise Mar 29 '16 at 21:40
  • But for 1.11400 and 1.12400 I need 1.11 and 1.12 accordingly. RoundingMode.CEILING don't give these results. – hqmr Mar 30 '16 at 06:23