0

I have been looking for answers here re: rounding and BigDecimal, but I am having trouble. Can someone help?

The actual result of the below division is 11.469...

        BigDecimal a = new BigDecimal(0.32);
        
        BigDecimal b = new BigDecimal(2.79);
        
        BigDecimal diffPercent = (a.divide(b, 2, RoundingMode.HALF_EVEN)).multiply(HUNDRED);  // 11.00
        BigDecimal diffPercent = (a.divide(b, 4, RoundingMode.HALF_EVEN)).multiply(HUNDRED);  // 11.4700

How can I get 11.47 (two decimal places)?

chocalaca
  • 330
  • 2
  • 17

2 Answers2

1
BigDecimal bg = new BigDecimal("11.468");
MathContext mc = new MathContext(3); // 3 precision

// bg1 is rounded using mc
final BigDecimal round = bg.round(mc, RoundingMode.CEILING);
System.out.println(round);

Posting as this is another example of how to round

royB
  • 12,779
  • 15
  • 58
  • 80
1

Instead of multiplying by BigDecimal(100), move the decimal point to the right:

BigDecimal diffPercent = (a.divide(b, 4, RoundingMode.HALF_EVEN)).movePointRight(2)

Output: 11.47

This works because moving the decimal point only adjusts the scale of the BigDecimal.

Joni
  • 108,737
  • 14
  • 143
  • 193