1. Basic functions: floor, ceil, round
If you’ve only just started programming, rounding can seem like something “for accountants” or “for Excel”. In practice, it shows up much earlier: as soon as you start dividing numbers and getting fractions, you almost immediately want either to print the result nicely, or to apply a rule like “round up”, or to count how many whole units cover a fractional amount.
Imagine a typical everyday scenario. Your room length is 3.2 meters, and you buy baseboard in 1-meter pieces. You need 4 pieces, not 3 (that is, rounding up). Or you calculate a discount and want to display a price with two digits after the decimal point. Or you compute “how many pages are left”, and fractional pages don’t make anyone happy. In programming, this happens all the time — which is exactly why Kotlin’s standard library provides a whole set of rounding functions in the kotlin.math package.
floor(x): mathematical rounding down
When people say “round down”, beginners often hear “just drop the fractional part”. That confusion is dangerous. floor(x) rounds a number to the smaller integer (that is, “down along the number line”, toward minus infinity). By definition, floor(x) is rounding to an integer toward negative infinity.
Why does this matter? Because for positive numbers, “rounding down” and “dropping the fraction” look the same, but for negative numbers they suddenly diverge. And negative numbers are exactly what most often “expose” misunderstandings.
Mini example: floor for positive and negative values
import kotlin.math.floor
fun main() {
println(floor(3.14159)) // 3.0
println(floor(10.0)) // 10.0
println(floor(-1.1)) // -2.0
}
Notice: floor(-1.1) returns -2.0, because -2 is less than -1.1, while -1 is greater. That is what “down the axis” means.
ceil(x): mathematical rounding up
Now the symmetric operation. ceil(x) rounds a number to the larger integer (that is, “up along the number line”, toward plus infinity). Formally, this is rounding toward positive infinity.
It’s extremely useful when you’re counting whole units to “be sure you have enough”: how many boxes you need, how many buses you need, how many full meters of material you need to buy. If floor is “how many whole units definitely fit”, then ceil is “how many whole units are needed to cover everything”.
Mini example: ceil for positive and negative values
import kotlin.math.ceil
fun main() {
println(ceil(3.14159)) // 4.0
println(ceil(10.0)) // 10.0
println(ceil(-1.1)) // -1.0
}
Note how the negative value behaves: ceil(-1.1) = -1.0, because -1 is greater than -1.1.
round(x): round to the nearest
The most “familiar” rounding is “to the nearest integer”. Kotlin has a function round(x) that rounds to the nearest integer, but it has an important nuance: if the number is exactly in the middle (for example, 2.5), Kotlin rounds to the nearest even (so-called bankers rounding).
It sounds a bit like “math decided to play fair”, but there is a reason: for large volumes of data, this reduces the accumulation of systematic error (not “always up” and not “always down”).
Mini example: round and “halves”
import kotlin.math.round
fun main() {
println(round(3.49)) // 3.0
println(round(3.51)) // 4.0
println(round(3.5)) // 4.0 (between 3 and 4 -> to even 4)
println(round(2.5)) // 2.0 (between 2 and 3 -> to even 2)
}
If you expected 2.5 to become 3.0, you’re not alone. This is one of those moments when it’s important not to “guess”, but to remember the rule. Programming is not mathematics.
3. toInt() and why it’s not rounding
floor/ceil/round return Double
Sometimes it seems like if we rounded a number to an integer, then the type should become Int as well. But floor, ceil, and round live in the world of real numbers and return Double (or Float for the Float versions). This is convenient: you can keep computing complex expressions as Double and only at the end, if needed, convert the result to Int.
A useful mental model is simple: rounding is a mathematical operation, while toInt() is a type conversion. These are different concepts, even if they sometimes produce the same digits.
toInt() truncates toward zero
Here is the main character of today’s trap. The toInt() method on Double does not do “mathematical rounding”; it performs a conversion: the fractional part is discarded toward zero.
That means 3.99.toInt() becomes 3, and -3.99.toInt() becomes -3. Not -4. This is a very common source of “why did my calculations break for negative numbers?”
Mini example: toInt() for plus and minus
fun main() {
println(3.99.toInt()) // 3
println(-3.99.toInt()) // -3
println(3.0.toInt()) // 3
}
If you just thought “right, it cuts off the fraction”, the important clarification is: it cuts toward zero, not down along the axis. That is the key point.
Nuance: NaN and very large numbers
toInt() also protects you from some extremes. If the value is NaN, it returns 0. If the number is too large or too small for Int, the result becomes Int.MAX_VALUE or Int.MIN_VALUE.
We won’t dive into these cases today, but it’s useful to know that toInt() is not just “cut off the fraction”, but also “fit into the Int range”.
Where exactly toInt() differs from floor/ceil/round
If you take a positive number 7.9, then:
- floor(7.9) = 7.0
- 7.9.toInt() = 7
And it’s easy to make the mistake of thinking these are the same thing.
Now take a negative value -7.9:
- floor(-7.9) = -8.0
- (-7.9).toInt() = -7
The difference is fundamental: floor goes toward minus infinity, while toInt() goes toward zero.
Table for reinforcement
|
|
|
|
|
|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Here, floor/ceil follow the mathematical definitions, round rounds to the nearest with “ties to even”, and toInt() performs a conversion by discarding the fractional part toward zero.
4. Practical rounding techniques
How to get an Int with the rule you need
Often you need an Int: for example, the number of items, the number of pages, the number of packages. But you want to round using the floor/ceil/round rule, not “toward zero”.
Then use a simple technique: first round as a Double, then convert to Int. Yes, in two steps. Yes, that’s normal. Kotlin won’t be offended.
Example: round up and get an Int
import kotlin.math.ceil
fun main() {
val metersNeeded = 3.2
val pieces = ceil(metersNeeded).toInt()
println(pieces) // 4
}
Example: round down and get an Int
import kotlin.math.floor
fun main() {
val fullBoxes = 9.99
val boxes = floor(fullBoxes).toInt()
println(boxes) // 9
}
Example: round to the nearest and get an Int
import kotlin.math.round
fun main() {
val rating = 4.6
val rounded = round(rating).toInt()
println(rounded) // 5
}
Rounding to N digits after the decimal point
Very often you need to round to 2 digits (prices, percentages). But round(x) rounds to an integer. What do you do? Use a school trick that shows up constantly in practice: multiply by 10N, round to an integer, then divide back.
It’s important to remember: we’re still in the Double world, and because of precision you can sometimes see a not-perfectly-pretty fraction. But as a baseline technique, it’s an excellent start.
Example: rounding to 2 digits
import kotlin.math.round
fun main() {
val x = 12.34567
val rounded2 = round(x * 100.0) / 100.0
println(rounded2) // 12.35
}
The idea is: x * 100 shifts the decimal point 2 digits to the right, round makes the number an integer, and / 100 shifts the decimal point back.
Mini scenario: a delivery price calculator
Now we’ll write a small (but solid) project that ties together everything you’ve learned. Let’s imagine we have a simple console program that calculates an order total, tax, and shipping. We don’t read input from the console, so we use constants in the code — rounding is what matters here.
Let’s assume:
- item price: subtotal
- tax is 7.5%: taxRate
- shipping is charged “per started kilogram” (that is, rounding up)
- we print the final total with 2 digits after the decimal point
Step 1: compute tax and round the total for display
import kotlin.math.round
fun main() {
val subtotal = 39.90
val taxRate = 0.075
val tax = subtotal * taxRate
val total = subtotal + tax
val totalPretty = round(total * 100.0) / 100.0
println("Total: $totalPretty") // Total: 42.89
}
The key point here: we rounded only for display. In real tasks, rules may be stricter (when and how to round), but today it’s enough to understand the mechanics.
Step 2: compute shipping using the “per started kilogram” rule
Now let’s add weight and the price per kilogram. If the weight is 2.1, you must pay as if it were 3 (rounding up).
import kotlin.math.ceil
fun main() {
val weightKg = 2.1
val pricePerKg = 3.0
val billedKg = ceil(weightKg).toInt()
val shipping = billedKg * pricePerKg
println("Billable weight: $billedKg kg") // Billable weight: 3 kg
println("Shipping: $shipping") // Shipping: 9.0
}
Note: ceil(weightKg) returns a Double, so toInt() is a separate step.
Step 3: why you can’t write weightKg.toInt() instead of ceil(weightKg)
And here is the moment of truth. For positive weights it might look “almost fine”, but the meaning is wrong: 2.1.toInt() gives 2, which means you undercharge for shipping.
fun main() {
val weightKg = 2.1
println(weightKg.toInt()) // 2 (this is NOT "per started", this is "truncate toward zero")
}
toInt() is not “round up”, and it’s not even “mathematical round down”. It’s a conversion that discards the fractional part toward zero.
Rounding selection flow
Next time you’re choosing between floor, ceil, round, and toInt(), it’s useful not to mentally try to “pick what seems right”, but to ask yourself one question: what rule does the task require?
flowchart TD
A["There is Double x"] --> B{"Is this for displaying to a person?"}
B -->|Yes| C["Round to N digits: round(x*10^N)/10^N"]
B -->|No| D{"Do you need a whole number of units?"}
D -->|Yes, to make sure it's ENOUGH| E["ceil(x) -> toInt()"]
D -->|Yes, how many fit for sure| F["floor(x) -> toInt()"]
D -->|No, just convert the type| G["x.toInt() (truncates toward zero)"]
This diagram is meant to remind you: toInt() is not “universal rounding”, but a separate semantic step.
5. Common mistakes when rounding and converting to Int
Mistake #1: thinking that toInt() is rounding.
Early on, it’s very tempting to think: “converted to Int — so I rounded it”. In reality, Double.toInt() discards the fractional part toward zero. Because of this, the “round down” logic breaks for negative values, and the “round up” logic is simply wrong in all cases.
Mistake #2: confusing “rounding down” with “toward zero”.
floor(x) rounds down along the number line, i.e., toward negative infinity. But toInt() and truncate(x) (if you encounter it) work toward zero. For positive numbers, the difference is barely visible, so the mistake hides and then “pops up” later at the worst possible moment.
Mistake #3: expecting round(2.5) to produce 3.0.
In Kotlin, round(x) uses the “ties to even” rule — halves round to the nearest even integer. If you’re writing an algorithm where behavior at .5 matters (for example, scores, ratings), make sure you verify what the task rules actually require.
Mistake #4: forgetting that ceil/floor/round return Double, and trying to “feed” it somewhere that expects an Int.
In Kotlin, this usually won’t compile (and that’s good). But beginners sometimes try to “force” the idea: since it’s 3.0, it must be an integer. No: the type is still Double. The correct path is rounding first (ceil/floor/round), then an explicit conversion (toInt()).
Mistake #5: rounding “to 2 digits” without scaling, or with the wrong scaling.
The trick round(x * 100.0) / 100.0 works precisely because 100 corresponds to two digits. If you accidentally multiply by 10 but divide by 100, you’ll get strange “magic” (and it will honestly be your magic, not Kotlin’s). Treat the scaling factor as part of the rule, not as a random number pulled from thin air.
GO TO FULL VERSION