1

I have refer this and did rounding of BigDecimal value then also I am getting above mentioned error. Please find code mentioned below. Thanks in advance:

BigDecimal val1 = new BigDecimal(494.10000001).setScale(8, BigDecimal.ROUND_UP);
BigDecimal val2 = new BigDecimal(693189.38625000).setScale(8, BigDecimal.ROUND_UP);
BigDecimal result = val1.divide(val2);
System.out.println(result);
senerh
  • 1,265
  • 10
  • 19
Tejal
  • 715
  • 1
  • 10
  • 37
  • try BigDecimal result=val1.divide(val2,8,RoundingMode.HALF_UP); – Amit Bera Feb 17 '18 at 08:53
  • 1
    The post you linked mentions `a.divide(b, 2, RoundingMode.HALF_UP)`, but that's not what you're doing, so I'm inclined to say this is just a duplicate of that, or a typographical error. – Bernhard Barker Feb 17 '18 at 09:06

2 Answers2

4

The answer was in that post, and stated multiple time also:

a.divide(b, 8, RoundingMode.HALF_EVEN);

try this for your divide statement, (the scale is 8 for your precision). What you're doing right now is dividing two large decimals, which results in an ultra large decimal answer, and you're not controlling the precision.

Rudy Velthuis
  • 27,909
  • 4
  • 45
  • 87
JakeTheSnake
  • 362
  • 1
  • 11
0

Please note that the divide method has its own optional rounding mode parameter:

BigDecimal result=val1.divide(val2, BigDecimal.ROUND_UP);
Mick
  • 905
  • 7
  • 16