Kotlin How to Convert Double to Int with Examples
In Kotlin, you can convert a
Double to an Int by calling the toInt() function on the double value, like val intValue = doubleValue.toInt().Examples
Input12.99
Output12
Input0.0
Output0
Input-5.75
Output-5
How to Think About It
To convert a double to an int in Kotlin, think about removing the decimal part since an int holds whole numbers only. The
toInt() function cuts off the decimal part without rounding, so you get just the integer portion of the double.Algorithm
1
Take the double value as input.2
Call the <code>toInt()</code> function on the double value.3
Store or return the resulting integer value.Code
kotlin
fun main() {
val doubleValue: Double = 12.99
val intValue: Int = doubleValue.toInt()
println(intValue) // Output: 12
}Output
12
Dry Run
Let's trace converting 12.99 to int using toInt()
1
Start with double value
doubleValue = 12.99
2
Convert to int
intValue = doubleValue.toInt() -> 12
3
Print result
Output: 12
| doubleValue | intValue |
|---|---|
| 12.99 | 12 |
Why This Works
Step 1: Using toInt() function
The toInt() function converts a double to an int by dropping the decimal part.
Step 2: No rounding happens
It simply truncates the decimal, so 12.99 becomes 12, not 13.
Step 3: Result is an integer
The result is a whole number stored as an Int type.
Alternative Approaches
Using Math.round() and converting to Int
kotlin
fun main() {
val doubleValue = 12.99
val intValue = Math.round(doubleValue).toInt()
println(intValue) // Output: 13
}This rounds the double to the nearest integer before converting, unlike toInt() which truncates.
Using floor() from kotlin.math and converting to Int
kotlin
import kotlin.math.floor fun main() { val doubleValue = 12.99 val intValue = floor(doubleValue).toInt() println(intValue) // Output: 12 }
This explicitly floors the value before converting, similar to toInt() but clearer for some.
Complexity: O(1) time, O(1) space
Time Complexity
Conversion using toInt() is a simple operation that runs in constant time.
Space Complexity
No extra memory is needed besides the output integer, so space is constant.
Which Approach is Fastest?
toInt() is fastest and simplest; rounding or flooring adds minor overhead but is still O(1).
| Approach | Time | Space | Best For |
|---|---|---|---|
| toInt() | O(1) | O(1) | Simple truncation without rounding |
| Math.round() then toInt() | O(1) | O(1) | Rounding to nearest integer |
| floor() then toInt() | O(1) | O(1) | Explicit floor before conversion |
Use
toInt() to quickly drop decimals when converting Double to Int in Kotlin.Expecting
toInt() to round the number instead of truncating the decimal part.