Java - limit number between min and max

后端 未结 7 710
耶瑟儿~
耶瑟儿~ 2020-12-06 08:53

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

7条回答
  •  一整个雨季
    2020-12-06 09:29

    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.

提交回复
热议问题