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
}
}
- The "this" keyword inside an extension function corresponds to the receiver object. it can also be remove
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