[英]simple android calculator returning too many zeros and wrong decimal point
因此,輸出“ H”給我的數字太長了,小數點在錯誤的位置,但否則整個數字都是正確的。 例:
333433.33333
是顯示的內容333.43
應該顯示
我懷疑罪魁禍首是
`h = (double) Math.round(h * 100000) / 100000;`
但是當我將其更改為h = (double) Math.round(h * 1000) / 1000;
它似乎沒有幫助。
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;
}
}
據我了解, h
相差1000倍,並且您的TextView
顯示了太多的小數點。 我建議:
1)在Calculate_H
中將h
除以1000。 (即, return h / 1000
)
2)使用String.format
在小數點后顯示所需的位數。 例如, txtAnswer.setText(String.format("H = %.2f", Calculate_H(F, A, C)))
將在小數點后顯示2位數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.