Java 从 EditText 到浮动的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4229710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String from EditText to float
提问by Espen
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:
我有一个将用于浮点数的 EditText。所以我试图从 EditText 读取文本并将其放入浮点变量中。但我似乎有一个文本浮动问题。这是我的线路:
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?
我试过使用 Float.parseFloat(string) 和一般的转换,但似乎没有任何作用。我可以在这里做什么?另外,有没有办法在将浮点数写入变量之前检查有效的浮点数?
采纳答案by Octavian A. Damiean
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.
valueOf()
如果Float
包装类将字符串转换为浮点数,则使用该方法。在这个例子中,我得到Editable
的是物体EditText
与getText()
上我所说的toString()
方法从中获得一个字符串。
Update:Totally right guys sorry. Time to increment my sheep counter.
更新:完全正确的人抱歉。是时候增加我的羊计数器了。
回答by Daniel
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.
如果您希望代码在使用十进制逗号而不是小数点的国家/地区工作,请不要使用 Float.valueOf()。