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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...