Kotlin: Condition that double-value is a "normal" number

663 views Asked by At

How can I test if a value of type Double in Kotlin is not Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN or some other special value?

I'd like to have something like require(Double.isNormal(x))

2

There are 2 answers

0
al3c On BEST ANSWER
9
Thomas Cook On

Sounds like you've answered your own question.... write a function that checks the 3 cases, and takes a lambda to run if the precondition is met:

fun ifNormal(double: Double, toDo: () -> Unit) {
    if (double != Double.POSITIVE_INFINITY 
        && double != Double.NEGATIVE_INFINITY 
        && double != Double.NaN) {
        toDo()
    }
}

Then use it like so:

ifNormal(1.0) {
  // Do stuff
}