0

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))

Moritz Groß
  • 1,352
  • 12
  • 30

2 Answers2

9

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/is-finite.html

require(x.isFinite()) is what you need.

al3c
  • 1,392
  • 8
  • 15
1

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
}
Thomas Cook
  • 4,371
  • 2
  • 25
  • 42