0

We have one page where we are fetching the data from database. one field "AmountEur" is there which is getting rounding off (using bigdecimal.ROUND_HALF_UP method) before showing it up on view page.

the code is like this :

final Object amountEur = result.get("mtmAmountEUR");
if (amountEur != null) {
BigDecimal mtmAmt = ((BigDecimal) amountEur ).setScale(0,   BigDecimal.ROUND_HALF_UP);
result.put("mtmAmount", mtmAmt);
}

With this code, i am facing one issue. suppose if the data fetched from db is 2650.5, then the data shown in the view page is 2650 only. ideally it should be 2651. on the other hand, If the data is 2650.55 in db, it is showing fine on view page i.e 2651. I do not know what is the problem with my code. Could someone please help.

user2326831
  • 151
  • 2
  • 14

1 Answers1

0

The following snippet:

    BigDecimal bd1=new BigDecimal("2650.499999");
    BigDecimal bd2=new BigDecimal("2650.5");
    BigDecimal bd3=new BigDecimal("2650.500001");


    BigDecimal rounded1=bd1.setScale(0,BigDecimal.ROUND_HALF_UP);
    BigDecimal rounded2=bd2.setScale(0,BigDecimal.ROUND_HALF_UP);
    BigDecimal rounded3=bd3.setScale(0,BigDecimal.ROUND_HALF_UP);

    System.out.println(bd1 + " -> " + rounded1);
    System.out.println(bd2 + " -> " + rounded2);
    System.out.println(bd3 + " -> " + rounded3);

Produces the expected output:

2650.499999 -> 2650
2650.5 -> 2651
2650.500001 -> 2651

There is something more subtle going on that a misunderstanding or bug in the rounding logic implemented by setScale(.,.).

Try printing out the BigDecimal value to see that you have 2650.5 and not 2650.499999 for example given you're using Number(26,6).

Persixty
  • 8,165
  • 2
  • 13
  • 35