Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
95 views
in Technique[技术] by (71.8m points)

java - String from EditText to float

I have an EditText for which will be using for a float number. So I'm trying to read the text from the EditText and put it into a float variable. But I seem to have a text to float problem. This is the line I have:

float Number = ( ( EditText )findViewById( R.id.edit_float ) ).getText();

I've tried using Float.parseFloat(string) and just general casting, but nothing seem to do it. What can I do here? Also, is there a way to check for a valid float number before writing it to a variable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this.

EditText edt = (EditText) findViewById(R.id.edit_float);
float number = Float.valueOf(edt.getText().toString());

You use the valueOf() method if the Float wrapper class to convert a string to a float. IN this example I get the Editable object of that EditText with getText() on which I call the toString() method to obtain a string from it.

Update: Totally right guys sorry. Time to increment my sheep counter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...