Search code examples
androidbigdecimaldivide

Why 1 divided by 1.1 doesn't work, even when I'm using BigDecimal in my code?


I'm trying to do a calculator with the 4 basic operations. I started using doubles to get the arguments from edittext, but I discovered the problem with decimal values. To avoid that, I used BigDecimal, but now the app is failing at some specific numbers, as 1/(1.1). I noticed only the divide function is wrecking the app, add,sub and multiply are working fine. I really would appreciate some help with this. Here's part of the code:

 div.setOnClickListener( 
        new View.OnClickListener(){

                @Override
            public void onClick(View v){


                    if(! num1 .getEditableText().toString().matches("") && !num2 .getEditableText().toString().matches(""))
                    {String valor1 =num1.getText().toString();
                    String valor2 =num2.getText().toString();
                    BigDecimal a = new BigDecimal(valor1);
                    BigDecimal b = new BigDecimal(valor2);
                    BigDecimal result = a.divide(b);

                    Toast.makeText(MainActivity.this,"="+result, Toast.LENGTH_LONG).show();
                    }                                                                           }


            });

Solution

  • If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.

    Use divide method like that

    a.divide(b, 2, RoundingMode.HALF_UP)
    where 2 is precision and RoundingMode.HALF_UP is rounding mode
    

    source:https://stackoverflow.com/a/4591216/1589566