Limit the number of decimals - JAVA

Asked

Viewed 63 times

-1

Hello!

I just started programming and I’m learning java. I’m trying to make my first app, which calculates the rule of three. I managed to make it work, but I had to transform the result of the calculation from double to String, because I was using the method. setText() to display the result. I have two doubts:

  1. Is there a method that displays a double in a Textview? (I’m currently using . setText())
  2. How do I limit the number of decimals that are displayed?

Also, if I’m doing something wrong or there’s a better way to develop the code, I accept suggestions.

Thank you in advance.


import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

    private EditText num1, num2, num3;
    private TextView resultado;
    private Button botaoCalcular;

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

        num1 = findViewById(R.id.editNum1);
        num2 = findViewById(R.id.editNum2);
        num3 = findViewById(R.id.editNum3);
        resultado = findViewById(R.id.textViewResultado);
        botaoCalcular = findViewById(R.id.buttonCalcular);
        }
    public void calcular(View view){
        String stringNumero1 = num1.getText().toString();
        String stringNumero2 = num2.getText().toString();
        String stringNumero3 = num3.getText().toString();
        double numero1 = Double.parseDouble(stringNumero1);
        double numero2 = Double.parseDouble(stringNumero2);
        double numero3 = Double.parseDouble(stringNumero3);

        //cálculo
        double resultadoCalculo = (numero2 * numero3) / numero1;
        String resultadoCalculoFinal = String.valueOf(resultadoCalculo);
        resultado.setText(resultadoCalculoFinal);


    }
}

Screenshot of the app: https://imgur.com/a/sHkrEOj

1 answer

-1


As you are converting a double to String, could use the format.

Replace:

String resultadoCalculoFinal = String.valueOf(resultadoCalculo);

Why is:

String resultadoCalculoFinal  = String.format("%.2f", resultadoCalculo);

Remember that the result will have comma, example: 19,58 You can replace if you need to replace a comma by a period or vice versa.

  • It worked, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.