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?
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.
float getFloatFrom(EditText txt) {
try {
return NumberFormat.getInstance().parse(txt.getText().toString()).floatValue();
} catch (ParseException e) {
return 0.0f;
}
}
Do NOT use Float.valueOf() if you want the code to work in countries that use decimal comma instead of decimal point.
String stext = editText.getText().toString();
float text = Float.parseFloat(stext);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.