-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:
- Is there a method that displays a double in a Textview? (I’m currently using . setText())
- 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
It worked, thank you!
– Natan Bartz