This article explores different ways to convert a floating-point value to the nearest integer in Kotlin.

For example, when x = 10.55f, the output should be 11 and for x = -10.55f, the output should be -11.

1. Using roundToInt() function

The standard solution is to use the roundToInt() function to round the floating-point value to the nearest integer. This function additionally convert a floating-point value x to Int.MAX_VALUE when x > Int.MAX_VALUE and to Int.MIN_VALUE when x < Int.MIN_VALUE.

Download Code

2. Using toInt() function

Typecasting in Kotlin simply truncates the floating-point value and does not round it to the nearest integer, as shown below:

Download Code

 
There’s a workaround for this.

To round the given floating-point positive value x, you can use the expression (x + 0.5).toInt(). Similarly, to round a floating-point negative value x, you can use the expression (x - 0.5).toInt(). This is demonstrated below:

Download Code

That’s all about converting a floating-point value to the nearest integer in Kotlin.