1

So I've got the following code which makes some calculations depending on user input and then shows the results in a textView.

public class DescentCalculator extends AppCompatActivity {

EditText num1, num2, num3;
TextView resu;
double startdecent;
double feetminute;

@Override
public void onCreate ( Bundle savedInstanceState ) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.descent);

    Toolbar mToolbar = (Toolbar) findViewById(R.id.mtoolbar);
    setSupportActionBar(mToolbar);

    Button add = (Button) findViewById(R.id.button11);
    num1 = (EditText) findViewById(R.id.altitude_fix);
    num2 = (EditText) findViewById(R.id.altitude_cruise);
    num3 = (EditText) findViewById(R.id.mach_speed);
    resu = (TextView) findViewById(R.id.answer);

    add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick ( View v ) {
            // TODO Auto-generated method stub

            String altfix = num1.getText().toString();
            String altcruise = num2.getText().toString();
            String machspeed = num3.getText().toString();


            startdecent = (Double.parseDouble(altcruise) - Double.parseDouble(altfix)) / 100 / 3;

            feetminute = (3 * Double.parseDouble(machspeed) * 1000);

            resu.setText(Double.toString(startdecent) + Double.toString(feetminute));


        }

    });
}

For example, if the user enters 7000 for the altcruise, 6000 for altfix and 0.30 for machspeed the app calculates the answer as 3.33333333333335899.999999999 which is technically right. I'd like the app to round up the answer and display 3.3 in this case.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
D. Popa
  • 37
  • 6

1 Answers1

1

Look at this answer: Round a double to 2 decimal places

This code snippet takes in a double and reads it into a BigDecimal and rounds it returning a double with n decimalplaces.

public static void main(String[] args){

    double myDouble = 3.2314112;

    System.out.print(round(n,1));

}

public static double round(double value, int places) {
    if (places < 0) throw new IllegalArgumentException();

    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(places, RoundingMode.HALF_UP);
    return bd.doubleValue();
}

This returns 3.2

Tacolibre
  • 110
  • 2
  • 12