Skip to content# Using floor() in Kotlin

### Understanding the floor() Function

### Syntax

### Example Use Cases

#### Scenario 1: Discount Calculation

#### Scenario 2: Conversion of Measurement Units

— Kotlin, Programming, Android Development — 1 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.

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.

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.floor2
3fun main() {4 val result = floor(5.8)5 println(result) // Output: 5.06}
```

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.

Let's consider a few practical scenarios where the `floor()`

function can be incredibly useful.

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.floor2
3fun main() {4 val originalPrice = 50.05 val discountPercentage = 206 val discountedPrice = originalPrice - (originalPrice * (discountPercentage / 100.0))7 val finalPrice = floor(discountedPrice)8 println(finalPrice) // Output: 40.09}
```

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.floor2
3fun main() {4 val feet = 10.55 val meters = floor(feet / 3.281)6 println(meters) // Output: 3.07}
```