Home > Enterprise >  Round up instead of down
Round up instead of down

Time:08-21

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:

  1. By using decimal format,

    fun Double.ceilRound():Int{
     return DecimalFormat("#").apply {
         roundingMode = RoundingMode.CEILING
     }.format(this).toInt()
    }
    
  1. 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
     }
    
  • Related