Skip to content
DeveloperMemos

Using floor() in Kotlin

Kotlin, Programming, Android Development1 min read

When working with numerical values in Kotlin, you often encounter scenarios where you need to round down a decimal number to the nearest whole number or to a specific decimal place. Kotlin provides a neat solution to this through the floor() function. In this article, we'll delve into the usage of floor() in Kotlin, explore its applications, and provide practical examples to illustrate its utility.

Understanding the floor() Function

The floor() function in Kotlin is a part of the kotlin.math package. Its primary purpose is to return the largest (closest to positive infinity) double value that is less than or equal to the given argument. This means that when you pass a floating-point number to the floor() function, it returns the largest integer that is less than or equal to the given number.

Syntax

The syntax for using the floor() function is quite straightforward. It takes a single parameter, which is the number you want to round down. Here's the basic syntax:

1import kotlin.math.floor
2
3fun main() {
4 val result = floor(5.8)
5 println(result) // Output: 5.0
6}

In this example, the floor() function takes the decimal number 5.8, and the result is 5.0, as it represents the largest integer that is less than or equal to 5.8.

Example Use Cases

Let's consider a few practical scenarios where the floor() function can be incredibly useful.

Scenario 1: Discount Calculation

Suppose you are developing an e-commerce application and need to calculate the discounted price of a product. You might offer a discount rate of 20% on certain items. When calculating the discounted price, you would need to round down the resulting price to ensure that customers are charged a precise amount. Here's how you can achieve this using the floor() function:

1import kotlin.math.floor
2
3fun main() {
4 val originalPrice = 50.0
5 val discountPercentage = 20
6 val discountedPrice = originalPrice - (originalPrice * (discountPercentage / 100.0))
7 val finalPrice = floor(discountedPrice)
8 println(finalPrice) // Output: 40.0
9}

Scenario 2: Conversion of Measurement Units

Consider a situation where you need to convert measurements from one unit to another, such as converting feet to meters while ensuring that the result is rounded down to the nearest whole number. The floor() function can be utilized in this context as well:

1import kotlin.math.floor
2
3fun main() {
4 val feet = 10.5
5 val meters = floor(feet / 3.281)
6 println(meters) // Output: 3.0
7}