In the Kotlin programming language, .toInt() rounds down. how do I round up instead?
CodePudding user response:
You can use ceil(double x)
to round any double to a higher value.
Or use roundToInt
.
fun main() {
val x = 10.55f
val y: Int = x.roundToInt()
println("y = $y") // y = 11
}
CodePudding user response:
use .ceil
math.ceil(x).toInt()
CodePudding user response:
By using decimal format,
fun Double.ceilRound():Int{ return DecimalFormat("#").apply { roundingMode = RoundingMode.CEILING }.format(this).toInt() }
fun Double.roundCeil():Int = ceil(this).toInt()
fun main() { val a = 5.35 println(a.ceilRound()) //6 println(a.roundCeil()) //6 val b = 5.75 println(b.ceilRound()) //6 println(b.roundCeil()) //6 }