How can I show only two decimals in the operation?

3

I'm working with android studio and I want the answer to only show it to me with only two decimals, I do not know where that is done, only I can be with format ()

public class MainActivity extends AppCompatActivity implements
        View.OnClickListener {
    private Button btnSuma, btnResta, btnProducto, btnDivision;
    private EditText numero1, numero2;
    private TextView resultado;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //enlazar los objetos con los elementos xml
    numero1 = (EditText)findViewById(R.id.n1);
    numero2 = (EditText)findViewById(R.id.n2);
    resultado = (TextView)findViewById(R.id.resultado);
    //colocar el cursor en el primer EditText
    numero1.requestFocus();
    btnSuma = (Button)findViewById(R.id.btnsumar);
    btnResta = (Button)findViewById(R.id.btnrestar);
    btnProducto = (Button)findViewById(R.id.btnmultiplicar);
    btnDivision = (Button)findViewById(R.id.btndividir);
    resultado = (TextView)findViewById(R.id.resultado);
    //escuchar los onClick de los botones
    btnSuma.setOnClickListener(this);
    btnResta.setOnClickListener(this);
    btnProducto.setOnClickListener(this);
    btnDivision.setOnClickListener(this);
}
public void onClick(View v) {
    //declaramos las variables
    String valor1 = "", valor2 = "", mensaje1="", res="";
    float num1 = 0, num2 = 0, total = 0;
    //Tomar los valores o dar mensaje de error
    try {valor1 = numero1.getText().toString();
        valor2 = numero2.getText().toString();
        //convertirlos a float
        num1 = Float.parseFloat(valor1);
        num2 = Float.parseFloat(valor2);
        //controlar el onClick según el id del botón
        switch (v.getId()) {
            case R.id.btnsumar:
                total = num1 + num2;
                mensaje1 = "SUMA: " + total;
                numero1.setText("");
                numero2.setText("");
                break;
            case R.id.btnrestar:
                total = num1 - num2;
                mensaje1 = "RESTA: " + total;
                numero1.setText("");
                numero2.setText("");
                break;
            case R.id.btnmultiplicar:
                total = num1 * num2;
                mensaje1 = "PRODUCTO: " + total;
                numero1.setText("");
                numero2.setText("");
                break;
            case R.id.btndividir:
                total = num1 / num2;
                mensaje1 = "DIVISIÓN: " + total;
                numero1.setText("");
                numero2.setText("");
                break;
            case R.id.salir:
                finish();
                break;
            default:
                break;
        }
    }catch (Exception e) {
        //mensaje de error
        Toast.makeText(this, "Ingrese todos los datos",
                Toast.LENGTH_SHORT).show();
    }
    //salida de datos
    resultado.setText(mensaje1);
}



}

THE XML:

<RelativeLayout
    android:layout_width="368dp"
    android:layout_height="495dp"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="19dp"
        android:text="OPERACIONES BASICAS"
        android:textSize="18sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/textView"
        android:layout_marginLeft="35dp"
        android:layout_marginStart="35dp"
        android:layout_marginTop="30dp"
        android:text="Numero 1:"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/n1"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberDecimal"
        android:layout_alignBaseline="@+id/textView2"
        android:layout_alignBottom="@+id/textView2"
        android:layout_centerHorizontal="true" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_alignStart="@+id/textView2"
        android:layout_below="@+id/n1"
        android:layout_marginTop="49dp"
        android:text="Numero 2:"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/n2"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberDecimal"
        android:layout_alignBottom="@+id/textView3"
        android:layout_alignLeft="@+id/n1"
        android:layout_alignStart="@+id/n1" />

    <Button
        android:id="@+id/btnsumar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Suma"
        android:layout_below="@+id/btnrestar"
        android:layout_toLeftOf="@+id/n2"
        android:layout_toStartOf="@+id/n2" />

    <Button
        android:id="@+id/btnrestar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Resta"
        android:layout_below="@+id/n2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="32dp" />

    <Button
        android:id="@+id/btnmultiplicar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="multiplicar"
        android:layout_below="@+id/btnsumar"
        android:layout_toRightOf="@+id/textView3"
        android:layout_toEndOf="@+id/textView3"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp" />

    <Button
        android:id="@+id/btndividir"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="dividir"
        android:layout_below="@+id/btnrestar"
        android:layout_toRightOf="@+id/n2"
        android:layout_toEndOf="@+id/n2" />

    <TextView
        android:id="@+id/resultado"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_alignStart="@+id/textView3"
        android:layout_below="@+id/btnmultiplicar"
        android:layout_marginTop="15dp"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/salir"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_alignEnd="@+id/resultado"
        android:layout_alignRight="@+id/resultado"
        android:layout_below="@+id/resultado"
        android:layout_marginEnd="26dp"
        android:layout_marginRight="26dp"
        android:layout_marginTop="18dp"
        android:text="salir"
        android:textSize="10sp" />
</RelativeLayout>

    
asked by alvin 05.09.2017 в 22:20
source

3 answers

3

You can create a method to apply it in total in all the operations to get the message with the desired value to 2 digits, of the fraction, examples:

mensaje1 = "SUMA: " + obtieneDosDecimales(total);
...
...
mensaje1 = "DIVISIÓN: " + obtieneDosDecimales(total);

for this define a format with maximum 2 digits of the fraction, using the method:

  

setMaximumFractionDigits () : Set the maximum number of digits   allowed in the fraction portion of a number.

this would be the method:

private String obtieneDosDecimales(float valor){
    DecimalFormat format = new DecimalFormat();
    format.setMaximumFractionDigits(2); //Define 2 decimales.
    return format.format(valor);
}
    
answered by 05.09.2017 / 23:59
source
3

You can use the DecimalFormat class that allows you to apply a format to numbers with decimals.

An example of using DecimaFormat:

DecimalFormat formato = new DecimalFormat();
formato.setMaximumFractionDigits(2); //Numero maximo de decimales a mostrar
System.out.println(formato.format(numeroConDecimales));

Here is a link to the DecimalFormat documentation by if you want to know more.

    
answered by 05.09.2017 в 22:25
1

You can do it with the following example code:

        DecimalFormat formato = new DecimalFormat("$0.00");
        System.out.println("El promedio es: " + formato.format(promedio));

With promedio being a variable previously established and managed.

    
answered by 07.09.2017 в 04:09