Reputation: 117
Does anyone know how to parse a double from an EditText?
I know how to do it, but it isn't the right way I think. Does anyone have best practises?
Thank you.
Upvotes: 2
Views: 18493
Reputation: 1
Parse a double from an EditText (Kotlin)
toDouble() function works great but if the string is not a valid representation of a number. Throw NumberFormatException Exception.
toDoubleOrNull() function returns a double value. if the string is not a valid representation of a number return 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 using Extension 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
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)
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
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
Upvotes: 0
Reputation: 7376
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();
}
Upvotes: 10
Reputation: 4487
Whatever you type in EditText is String.
How to check if edittext is empty?
String str = edit_text.getText().toString();
if (str.trim().equals("")
Toast.makeText(getApplicationContext(),
"EditText is empty.",
Toast.LENGTH_SHORT).show();
Upvotes: 1