向上取整,而不是向下取整。

3
在 Kotlin 编程语言中,.toInt() 向下取整。那么我该如何向上取整呢?
3个回答

4
你可以使用 ceil(double x) 将任何 double 值向上舍入。
或者使用 roundToInt
fun main() {
    val x = 10.55f
 
    val y: Int = x.roundToInt()
    println("y = $y")            // y = 11
}

1

使用 .ceil

math.ceil(x).toInt()

0
使用十进制格式, 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
     }
    
  • 这段代码定义了一个扩展函数`roundCeil()`,它可以将浮点数向上取整并转换为整型。在`main()`函数中,我们定义了两个浮点数`a`和`b`,并分别调用了`ceilRound()`和`roundCeil()`函数来进行向上取整操作。最终输出结果均为6。

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接