I want to return the number as long as it falls within a limit, else return the maximum or minimum value of the limit. I can do this with a combination of Math.min
I understand this was asked for Java. In Android world, it's common to use Kotlin
and Java combined. In case some Kotlin user reached here (just like me), then they can use coerceIn
extension function:
Kotlin Code:
println(10.coerceIn(1, 100)) // 10
println(10.coerceIn(1..100)) // 10
println(0.coerceIn(1, 100)) // 1
println(500.coerceIn(1, 100)) // 100
Read more on official Kotlin Documentation.