How to call setText() using a Float? [duplicate]

2019-09-25 14:04发布

This question already has an answer here:

i tried to call the setText() using the float but it dosnt seem to work can somone help me fix the problem?

public class Bmi extends MainActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bmi);
        final EditText h = (EditText)findViewById(R.id.editText2);
        final EditText w = (EditText)findViewById(R.id.editText3);
        final TextView r = (TextView)findViewById(R.id.textView4);
        Button calculate = (Button) findViewById(R.id.button1);

        calculate.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {

                float height=0;
                float weight=0;
                float result=0;

                height= Float.parseFloat(h.getText().toString());
                weight= Float.parseFloat(w.getText().toString());

                result = (weight/(height * height));

                r.setText(result);
            }
        });
    }
}

im trying to make a simple bmi calculator just as practice but im having issues on making it work

3条回答
Root(大扎)
2楼-- · 2019-09-25 14:14

You can use

r.setText(String.valueOf(result));
查看更多
做个烂人
3楼-- · 2019-09-25 14:15

You should convert your float to a String by

r.setText(String.valueOf(result));

Or the quick and dirty way

r.setText("" + result);

If you want it localized (Dot or Comma seperated decimal number)

String text = NumberFormat.getInstance(YOURCONTEXT.getResources().getConfiguration().locale).format(result);
r.setText(text);

Just replace YOURCONTEXT with MainActivity.this if you are in the MainActivity or getActivity() if you are in a Fragment

If you want to set min or max fraction digits try this:

NumberFormat numberformat = NumberFormat.getInstance(YOURCONTEXT.getResources().getConfiguration().locale);
numberformat.setMaximumFractionDigits(2);
numberformat.setMaximumIntegerDigits(1);
numberformat.setMinimumFractionDigits(2);
String text = numberformat.format(result);
r.setText(text);
查看更多
【Aperson】
4楼-- · 2019-09-25 14:33

In order to display float value inside TextView you'll need to convert it to String first.

You can convert any primitive data type(int, float, double,boolean,etc) to String by using String.valueOf(value) method.

Here value is the variable which you want to convert to String.

You can use

String str = String.valueOf(result);
r.setText(str);

Alternatively

r.setText(String.valueOf(result));

Please comment if further help is required.

查看更多
登录 后发表回答