简体   繁体   中英

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

            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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM