Float Range in Kotlin
You can define a floating point range in Kotlin using ..
operator just like an integer range.
The syntax to define a floating point range [x, y] is
x..y
For example, 1.4..3.7
is a floating point range that starts at 1.4
and ends at 3.7
.
Theoretically, there are indefinite number of elements in a floating point range. Therefore, we cannot iterate over a float range. But we can do operations like checking if a specific float value is in this range, compare a float range with another, or check if the float range is empty.
Check if float value 3.14159 is in the float range 1.54..6.24
In the following program, we take an float range 1.54..6.24
, and check if 3.14159 is in this range.
Kotlin Program
fun main() {
val myRange = 1.54..6.24
val pi = 3.14159
if ( myRange.contains(pi) ) {
println("$pi is present in $myRange")
} else {
println("$pi is not present in $myRange")
}
}
Output
3.14159 is present in 1.54..6.24