89DEVs

# Python: How to round down?

```Use the int() function or the floor() method of the math module to round down float values in Python. If the math module is not needed for other operations use int() to minimize overhead.

The caveat with rounding down float values is that if the float value contains too many digits it will be rounded up at compile time.

use int() to round down

```
# round down using int()
myFloat = 1.99
rounded = int(myFloat)
print(rounded)
```

Using the int() function returns a rounded down integer for the float value. In this case 1.

1

use math.floor() to round down

An alternative approach is to import the math module and use the floor() method to round down float values.

```
# round down using math.floor()
import math
myFloat = 1.99
rounded = math.floor(myFloat)
print(rounded)
```

Using the floor() method of the math module the same integer is returned for the float value.

1

Caveat be aware of too many digits

If we have more digits than a float value can represent it is rounded up at compile time. This is not an error of the functions we use, but rather a limitation or more precisely wrong usage of the float type.

```
# round down caveat
myFloat = 1.999999999999999999
rounded = int(myFloat)
print(rounded)
```

In this example 2 instead of 1 is returned because the float contains too many digits.

2

Other rounding operations in Python

Python offers a variety of other rounding operations:

To round up use math.ceil() or numpy.ceil() methods.
To round to nearest integer use the round() function or numpy.round().
To round to 2 decimals use the built-in round() function.
To round to 5 (or any other number) use a custom function.```