-1

I know, there are dozens of topic like this in site but I am having trouble with 3 problems and I couldnt figure out all of them at the same time.

Actually, I am trying to make a calculator for Android but sometimes I cannot get what I am expected to.

A part of my code is;

}else if(operator.equals("/")){

            if(resultScreen.indexOf("/")==0){
                strNum2 = resultScreen.substring(resultScreen.indexOf("/")+1,resultScreen.length());
                intNum1 = result;
            }else{
                strNum1 = resultScreen.substring(0,resultScreen.indexOf("/"));
                strNum2 = resultScreen.substring(resultScreen.indexOf("/")+1,resultScreen.length());
                intNum1 = new BigDecimal(strNum1);
            }

            intNum2 = new BigDecimal(strNum2);


            if(intNum2.equals(0)){
                tvScreen.setText("Err");
                resultScreen ="";
            }else{
                result = intNum1.divide(intNum2);

                resultScreen = result.toString();

                tvScreen.setText(resultScreen);
                resultScreen ="";
            }
        }

When I try to;

22/7

It comes up;

3

How can I fix that?

By the way, I want to keep the exact value of decimal.

  • Please read the javadoc about divide: https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html (and see https://ideone.com/Fd197W) –  Nov 22 '16 at 06:37
  • I think its a duplicate of this. http://stackoverflow.com/questions/4591206/arithmeticexception-non-terminating-decimal-expansion-no-exact-representable – msagala25 Nov 22 '16 at 06:38

1 Answers1

2

This works

    BigDecimal a = new BigDecimal("22");
    BigDecimal b = new BigDecimal("3");
    BigDecimal res = a.divide(b, 2, RoundingMode.HALF_UP);
    System.out.println(res);

The key thing is to have a roundingMode else if the value can not be represented exactly an Exception will be thrown.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64