Pregunta

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();
                    }                                                                           }


            });
¿Fue útil?

Solución

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

Otros consejos

It crashes on an ArithmeticException because the result is a number with infinite decimals.

From http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html

"In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3. 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"

In your country it may be ',' and not '.'

String valor1 = num1.getText().toString().replace('.', ',');

Try this and tell us if it works !

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top