Hey I working in kotlin android. The string is com...
# android
v
Hey I working in kotlin android. The string is coming from server and it might be contains digit, character, empty string or null value. I want to convert that value in double because I want to compare value. So is there any better way to check that string only contain digit value and not empty or null in a kotlin way. The list is huge so I want a efficient way. Price.kt
Copy code
data class Price(
  var value: String? = null
)
main.kt
Copy code
val defaultValue : Double = 4.23
val list = listOf(Price("2.33"), Price("fr23"), Price(""), Price(null), Price("4.23"), Price("12.23"))

list.forEach{
   if(it == defaultValue){
      println("Found It")
   }
}
h
This might work
Copy code
fun String?.toProperDouble(): Double {
    return try {
        this?.toDouble() ?: (-1).toDouble()
    } catch (ex: NumberFormatException) {
        (-1).toDouble()
    }
}
t
the exception handling is probably not the most efficient way
@Vivek Modi do you want your invalid strings filtered out before the comparison? Or do you want your invalid strings to also be compared against valid strings? If you want invalid strings compared to valid strings, maybe Double.NaN is an appropriate value for those invalid strings.
In Kotlin, comparison with a NaN is unordered. According to IEE 754 If you want them ordered, maybe choose Positive or Negative infinity, which will always be greater or less than other doubles. Or, if you cast the doubles to Any, Kotlin changes it’s comparison to NaN being greater than Positive Infinity according to https://kotlinlang.org/docs/basic-types.html#floating-point-numbers-comparison
v
@Tim Oltjenbruns No I don't want to filter invalid string. Yes I want to compares invalid string to valid string. Do you know how can I solve this ?
t
yes, I just sent some helpful info!
v
@Tim Oltjenbruns Sorry I didn't get it. Can you please give me example?
t
if the string is null, empty, or otherwise does not parse to a double, you can return instead Double.NaN or Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY based on how you want your invalid strings to compare
toDoubleOrNull()
may also help
v
Copy code
fun String?.toProperDouble(): Double {
         this?.toDouble() ?: Double.NaN
 }
Is this correct ?
t
toDouble will throw an exception if it is invalid
use toDoubleOrNull
Do you want to attempt to remove the leading or trailing whitespace, if present? for example do you want to consider ” 1.0" or “1.0 ” as valid?
You could use
this?.trim()?.toDouble()
in that case, but it will take more memory
v
I don't think so server wil return whitespace value
Thanks it really help
👍 1
Copy code
fun String?.toProperDouble(): Double {
          this?.toDoubleOrNull() ?: Double.NaN
  }