Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 45 / 68

Rounding Numbers (floor, ceil, roundToInt)

In this lesson you will learn how to round numbers in Kotlin with floor, ceil, and roundToInt, and pick the right one for the job. This is for anyone searching for "Kotlin floor ceil roundToInt how to use".

floor() rounds down, ceil() rounds up, and .roundToInt() rounds to nearest. "Shave it down", "push it up", and "go to whichever is closer" are useful mental labels.

The sample code shows how similar-looking decimals give different results: floor(3.7) gives 3.0, ceil(3.2) gives 4.0, and 3.5.roundToInt() gives 4. Notice that they are imported from the kotlin.math package.

A common stumbling block for beginners is that floor() and ceil() return a Double while .roundToInt() returns an Int. You need to keep the different return types in mind.

In real-world development the choice changes your results - handling fractions in monetary calculations, lining up decimal places for display - so pick deliberately.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)