Problem when counting with decimals on Android

2

I want to get 5% of any number and it has occurred to me in the following way:

public class Main4Activity extends AppCompatActivity {

    EditText uno;
    TextView tres, tresinvisible, multiplica, divide, haciendocuenta, haciendocuenta2;
    Button btn1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);

        uno = (EditText) findViewById(R.id.uno);
        tres = (TextView) findViewById(R.id.tres);
        tresinvisible = (TextView) findViewById(R.id.tresinvisible);
        multiplica = (TextView) findViewById(R.id.multiplica);
        divide = (TextView) findViewById(R.id.divide);
        haciendocuenta = (TextView) findViewById(R.id.haciendocuenta);
        haciendocuenta2 = (TextView) findViewById(R.id.haciendocuenta2);
        btn1 = (Button) findViewById(R.id.btn1);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int aux0 = Integer.valueOf(uno.getText().toString());
                int resultado = aux0;
                // envio el número a:
                tres.setText("" + resultado + " " + "es el resultado final");
                tresinvisible.setText("" + resultado);
                // aux2 es el número que escribo en mi editText para sacarle el 5%
                int aux2 = Integer.valueOf(tresinvisible.getText().toString());
                // aux3 es igual a 5
                int aux3 = Integer.valueOf(multiplica.getText().toString());
                // multiplico aux2 * aux3
                int casiresultado1 = aux2 * aux3;
                // envio el resultado a:
                haciendocuenta.setText("" + casiresultado1);
                //
                int aux4 = Integer.valueOf(haciendocuenta.getText().toString());
                // divide es igual a 100
                int aux5 = Integer.valueOf(divide.getText().toString());
                // divido aux4 * aux5
                int resultadofinal11 = aux4 / aux5;
                // envio el resultado a:
                haciendocuenta2.setText("" + resultadofinal11);
                //
                int aux6 = Integer.valueOf(tresinvisible.getText().toString());
                int aux7 = Integer.valueOf(haciendocuenta2.getText().toString());
                // resto aux6 - aux7
                int resultadofinal = aux6 - aux7;
                // envio el resultado final a:
                tres.setText("" + resultadofinal + " " + "es el resultado final");
            }
        });
    }
}

I imagine that it is not the best way, but it has worked well for me, I have left notes of how I have done each action so that the code is clearer, but of course my problem comes now. As you can see in my code the number from which I get 5% I write it in my EditText but if it is a number with decimals the application closes. How can I solve it and be able to get 5% off numbers with decimals too?

Thanks! And if you know how I could make a cleaner / shorter code I would also thank you, it's like I thought I could do it but I do not know if it's the best way ...

The logcat marks this when it stops:

  

java.lang.NumberFormatException: Invalid int: "570.5"

EDITO1:

public class Main4Activity extends AppCompatActivity {

    EditText uno;
    TextView tres;
    Button btn1;

    static final BigDecimal PORCENTAJE_CINCO = new BigDecimal("0.05");

    public BigDecimal calculaCincoPorCiento(BigDecimal numero) {
        return numero.multiply(PORCENTAJE_CINCO);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);

        uno = (EditText) findViewById(R.id.uno);
        tres = (TextView) findViewById(R.id.tres);

        btn1 = (Button) findViewById(R.id.btn1);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BigDecimal aux0 = new BigDecimal(uno.getText().toString());
                BigDecimal aux1 = new BigDecimal(String.valueOf(calculaCincoPorCiento(PORCENTAJE_CINCO)));
                aux1 = aux1.divide(aux0);
                tres.setText("" + aux1 + " " + "es el 5%");
            }
        });
    }
}

I have tried to get 5% with decimals, seeing the response of @LuiggiMendoza, but I do not get 5%, I guess I do it wrong. Can you help me? Thanks!

    
asked by UserNameYo 18.05.2017 в 02:02
source

2 answers

3

Use BigDecimal :

static final BigDecimal PORCENTAJE_CINCO = new BigDecimal("0.05");

public BigDecimal calculaCincoPorCiento(BigDecimal numero) {
    return numero.multiply(PORCENTAJE_CINCO);
}

You can create instances of BigDecimal using a string ( String ) as long as it complies with the valid format of a number, which is: <parte entera>[<separador de decimales><parte decimal>] , where:

  • <parte entera> : the digits of the whole part of the number
  • <separador de decimales> : point .
  • <parte decimal> : the digits that make up the decimal part of the number

Note that you could also achieve this with double but BigDecimal has the advantage that it respects decimals and the exact value of them, while double is stored as a set of bits and can lead to inaccuracies .

After your editing, I see that you have this line:

//bien
BigDecimal aux0 = new BigDecimal(uno.getText().toString());
//extraño
BigDecimal aux1 = new BigDecimal(String.valueOf(calculaCincoPorCiento(PORCENTAJE_CINCO)));

I see two problems here:

  • You need to calculate 5% of aux0 , not constant PORCENTAJE_CINCO . Therefore, the parameter you should send is aux0 .
  • The calculaCincoPorCiento method already returns an instance of BigDecimal . What you do is convert the result (an instance of BigDecimal ) to String using String.valueOf() and then create an instance of BigDecimal again. It can be noticed when dividing the line into sections (read in order 1, 2 and 3, which is the order of execution):

    BigDecimal aux1 =
        //3. A partir de ese string, se crea un nuevo BigDecimal
        new BigDecimal(
            //2. El resultado (un BigDecimal) se convierte a String
            String.valueOf(
                //1. Llamando al metodo que devuelveBigDecimal
                calculaCincoPorCiento(PORCENTAJE_CINCO)
            )
        );
    
  • I would think that you can rewrite this line to

    BigDecimal aux1 = calculaCincoPorCiento(aux0);
    
        
    answered by 18.05.2017 / 02:41
    source
    1

    Well it seems to me that you had almost correct the calculation just need to calculate 5% of aux0 :

    static final BigDecimal PORCENTAJE_CINCO = new BigDecimal("0.05");
    
    public BigDecimal calculaCincoPorCiento(BigDecimal numero) {
        return numero.multiply(PORCENTAJE_CINCO);
    }
    
     btn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    BigDecimal aux0 = new BigDecimal(uno.getText().toString());
                    BigDecimal aux1 = new BigDecimal(String.valueOf(calculaCincoPorCiento(PORCENTAJE_CINCO)));
    
                    //aux1 = aux1.divide(aux0);                     
                    aux1 = calculaCincoPorCiento(aux0);  //5% de aux0.
    
                    tres.setText(aux1 + " " + "es el 5% de " + aux0);
    
                }
            });
        }
    
        
    answered by 18.05.2017 в 17:19