Convert a floating-point value to nearest int in Kotlin
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.
|
1 2 3 4 5 6 7 8 |
import kotlin.math.roundToInt fun main() { val x = 10.55f val y: Int = x.roundToInt() println("y = $y") // y = 11 } |
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:
|
1 2 3 4 5 6 |
fun main() { val x = 10.55f val y: Int = x.toInt() println("y = $y") // y = 10 } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { val x = 10.55f val y: Int if (x > 0) { y = (x + 0.5).toInt() } else { y = (x - 0.5).toInt() } println("y = $y") // y = 11 } |
That’s all about converting a floating-point value to the nearest integer in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)