当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Issues facing while rounding off big decimal value

问题描述:

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.

网友答案:

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).

分享给朋友:
您可能感兴趣的文章:
随机阅读: