simple android calculator returning too many zeros and wrong decimal point

821 views Asked by At

So the output "H" in this gives me too long of a number with the decimal point in the wrong spot, but otherwise the whole number is correct. Example:

333433.33333 is what gets displayed 333.43 should be displayed

I suspect the culprint is

    `h = (double) Math.round(h * 100000) / 100000;`

But when I change it to h = (double) Math.round(h * 1000) / 1000; it doesn't seem to help.

public class DoFCalculator extends Fragment {

EditText txtF;
Spinner aSpinner, cSpinner;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.calculators_fragment_dof, container, false);


    Button button = (Button) rootView.findViewById(R.id.btn_Cal);
    aSpinner = (Spinner) rootView.findViewById(R.id.aSpinner);
    txtF = (EditText) rootView.findViewById(R.id.focal_length);
    cSpinner = (Spinner) rootView.findViewById(R.id.coc);
    final TextView txtAnswer = (TextView) rootView.findViewById(R.id.txt_H);



    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            String F = txtF.getText().toString();
            String A = aSpinner.getSelectedItem().toString();
            String C = cSpinner.getSelectedItem().toString();
            if (!F.isEmpty() ) {
                txtAnswer.setText("H = " + Calcullate_H(F, A, C) + "");
            } else {
                Toast.makeText(getActivity(), "All data Required", Toast.LENGTH_LONG).show();
            }
        }
    });


    return rootView;
}

private double Calcullate_H(String txtF, String txtA, String txtC) {
    double f = Double.parseDouble(txtF.toString());
    double A = Double.parseDouble(txtA.toString());
    double C = Double.parseDouble(txtC.toString());
    double h = ((f * f) / (A * C)) + f;
    h = (double) Math.round(h * 100000) / 100000;
    return h;
}


}
1

There are 1 answers

2
chessdork On

From what I understand, h is off by a factor of 1000, and your TextView is showing too many decimal points. I recommend:

1) Divide h by 1000 in Calculate_H. (i.e., return h / 1000)

2) Use String.format to show the desired number of digits after the decimal point. For example, txtAnswer.setText(String.format("H = %.2f", Calculate_H(F, A, C))) will show 2 digits after the decimal point.