[英]How to get double from EditText the right way?
Does anyone know how to parse a double from an EditText?有谁知道如何从 EditText 解析双精度值?
I know how to do it, but it isn't the right way I think.我知道该怎么做,但这不是我认为的正确方式。 Does anyone have best practises?有没有人有最佳实践?
Thank you.谢谢你。
you can try this:你可以试试这个:
double value;
String text =your_edittext.getText().toString();
if(!text.isEmpty())
try
{
value= Double.parseDouble(text);
// it means it is double
} catch (Exception e1) {
// this means it is not double
e1.printStackTrace();
}
Whatever you type in EditText is String.无论您在 EditText 中键入什么,都是字符串。
How to check if edittext is empty?如何检查edittext是否为空?
String str = edit_text.getText().toString();
if (str.trim().equals("")
Toast.makeText(getApplicationContext(),
"EditText is empty.",
Toast.LENGTH_SHORT).show();
Parse a double from an EditText (Kotlin)从 EditText (Kotlin) 解析双精度
toDouble() function works great but if the string is not a valid representation of a number. toDouble()函数效果很好,但如果字符串不是数字的有效表示。 Throw NumberFormatException Exception.抛出NumberFormatException异常。
toDoubleOrNull() function returns a double value. toDoubleOrNull()函数返回一个双精度值。 if the string is not a valid representation of a number return null如果字符串不是数字的有效表示,则返回null
Implementation执行
fun parseToDouble(value :Editable): Double {
if(value.isNotEmpty()){
val result = value.trim().toString().toDoubleOrNull()
if(result != null)
return result
else
return 0.0
}else {
return 0.0
}
}
Or above code can be simplified usingExtension functions或者可以使用扩展函数简化上面的代码
fun Editable.parseToDouble(): Double {
if(this.isNotEmpty()){
val result = this.trim().toString().toDoubleOrNull()
if(result != null)
return result
else
return 0.0
}else {
return 0.0
}
}
Or above code can be simplified using Kotlin When expression或者上面的代码可以使用 Kotlin When 表达式简化
fun Editable.parseToDouble(): Double {
return when(isNotEmpty()){
true -> {
val result = trim().toString().toDoubleOrNull()
if(result != null) result else 0.0
}
else -> 0.0
}
Or above code can be simplified by Convert to expression body ( “return” vs expression body )或者上面的代码可以通过Convert to expression body来简化( “return” vs expression body )
fun Editable.parseToDouble(): Double = when(isNotEmpty()){
true -> {
val result = trim().toString().toDoubleOrNull()
if(result != null) result else 0.0
}
else -> 0.0
}
Or above code can be simplified using Kotlin Elvis Operator或者上面的代码可以使用 Kotlin Elvis Operator进行简化
fun Editable.parseToDouble() = when(isNotEmpty()){
true -> trim().toString().toDoubleOrNull()?: 0.0
else -> 0.0
}
Simplest version (best)最简单的版本(最佳)
fun Editable.parseToDouble() = trim().toString().toDoubleOrNull()?: 0.0
Or或者
fun Editable.parseToDouble() = toString().toDoubleOrNull()?: 0.0
Notes : similarly you can create parseToInt and parseToLong function注意:同样你可以创建parseToInt和parseToLong函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.