Doğukan Arslan Doğukan Arslan - 1 month ago 17
Android Question

Java BigDecimal Problems (String to BigDecimal - BigDecimal to String)

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("/")){

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

intNum2 = new BigDecimal(strNum2);

resultScreen ="";
result = intNum1.divide(intNum2);

resultScreen = result.toString();

resultScreen ="";

When I try to;


It comes up;


How can I fix that?

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


This works

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

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