-1

Here is my sample code which calculates the percentage of amounts, in the given example i am expecting the return to be 10 but its giving me 9.9. how do i round it up to 10?

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;


public class Test {


    public static final int AMOUNT_SCALE = 2;
    public static final int PRECISION_SIX = 6;
    private static BigDecimal tmp = new BigDecimal("100");
    public static final BigDecimal ONE_HUNDRED = tmp.setScale(0, RoundingMode.DOWN);
    public static final MathContext MATH_CONTEXT = new MathContext(PRECISION_SIX, RoundingMode.HALF_UP);

    public  static void main(String [] args){
         System.out.println(multiplyTwoNumbersAndDivideByOneHundredAmount(new BigDecimal(30), new BigDecimal(33.33))); ;
    }

    public static BigDecimal multiplyTwoNumbersAndDivideByOneHundredAmount(BigDecimal firstNumber, BigDecimal secondNumber) {
        return (firstNumber.multiply(secondNumber)).divide(ONE_HUNDRED,MATH_CONTEXT).setScale(AMOUNT_SCALE,RoundingMode.DOWN);
    }
}
user1224036
  • 988
  • 1
  • 15
  • 34

2 Answers2

1
.setScale(0, RoundingMode.HALF_UP);

Is what you're looking for.

xenteros
  • 15,586
  • 12
  • 56
  • 91
0

Pass the result through a BigInteger object:

BigInteger bi = new BigInteger(tmp);
xenteros
  • 15,586
  • 12
  • 56
  • 91
Ashish Patel
  • 163
  • 6