1

As you can see in the code, i can tell with Math.floor if the value of the variable is Decimal or Integer (if there is a easier way please tell me). If i sum 10 + 10 it gives me 20.0. what i want to to is if my sum is integer i dont want to show the decimal ".0", but if it is decimal i want to show them (like i show in my code)

    public void OnButtonClick(View ver) {

        //Atribuir as caixas de texto a varariavel
        EditText et1 = findViewById(R.id.et1);
        EditText et2 = findViewById(R.id.et2);
        TextView tv1 = findViewById(R.id.tv1);

        float input1;
        float input2;
        //Atribui o conteudo das ET para as variaveis e faz/apresenta a soma
        try {
            input1 = Float.parseFloat(et1.getText().toString());
            input2 = Float.parseFloat(et2.getText().toString());
            float sum = input1 + input2;

            if (sum >  Math.floor(sum)){
                //set text of tv1 with decimals here
                Toast.makeText(getApplicationContext(), "Decimal", Toast.LENGTH_SHORT).show();
            }
            else{
                //set text of tv1 with only integers here
                Toast.makeText(getApplicationContext(), "Integer", Toast.LENGTH_SHORT).show();
            }

            tv1.setText(String.valueOf(sum));

        }
        catch(NumberFormatException ex) {
            //Se estiver vazio msg de erro
            Toast.makeText(getApplicationContext(), "Preencha os campos", Toast.LENGTH_SHORT).show();

        }

    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Tiago Machado
  • 355
  • 7
  • 24
  • You can use `if(sum % 1 != 0) { [here goes your decimal code] } else { [cast your float to an int (removes decimals)] }` Otherwise you can use that approach https://stackoverflow.com/questions/11826439/show-decimal-of-a-double-only-when-needed – Oliver Adam Nov 28 '17 at 16:45

1 Answers1

0

The problem is that you're calling String.valueOf(float) which will return the number with a dot. Try this:

 input1 = Float.parseFloat(et1.getText().toString());
 input2 = Float.parseFloat(et2.getText().toString());
 float sum = input1 + input2;
 String output;

 if (sum >  Math.floor(sum)){
     Toast.makeText(getApplicationContext(), "Decimal", Toast.LENGTH_SHORT).show();
     output = String.valueOf(sum); // pass it as a float
 }
 else{
     Toast.makeText(getApplicationContext(), "Integer", Toast.LENGTH_SHORT).show();
     output = String.valueOf((int) sum); // casts sum to int, removing the ".0"
 }

 tv1.setText(output);
Gabriel Costa
  • 341
  • 1
  • 10