Borislav Hadzhiev
Last updated: Jul 12, 2022
Check out my new book
Use the math.floor()
method to round a float down to the nearest integer,
e.g. result = math.floor(3.999)
. The math.floor
method returns the largest
integer less than or equal to the provided number.
import math # ✅ round float down to nearest integer using math.floor() result_1 = math.floor(3.999) print(result_1) # 👉️ 3 result_2 = math.floor(3.14) print(result_2) # 👉️ 3 result_3 = math.floor(-3.6) print(result_3) # 👉️ -4 # -------------------------------------------------- # ✅ round float down to nearest integer using int() result_4 = int(3.999) print(result_4) # 👉️ 3 result_5 = int(3.14) print(result_5) # 👉️ 3 result_6 = int(-3.6) print(result_6) # 👉️ -3
We used the math.floor()
method to round a floating-point number down to the
nearest integer.
import math print(math.floor(6.99)) # 👉️ 6 print(math.floor(6.01)) # 👉️ 6 print(math.floor(-6.01)) # 👉️ -7
The math.floor method returns the largest integer less than or equal to the provided number.
math.floor()
method rounds towards negative infinity.This is different than the int()
class, which rounds towards zero.
Use the int()
class to round a float down to the nearest integer, e.g.
result = int(3.999)
. The int()
class truncates floating-point numbers
towards zero, so it will return an int
that represents the number without the
decimal places.
result_1 = int(3.999) print(result_1) # 👉️ 3 result_2 = int(3.14) print(result_2) # 👉️ 3 result_3 = int(-3.6) print(result_3) # 👉️ -3
The int class returns an integer object constructed from the provided number or string argument.
int()
class truncates towards zero.print(int(-11.1)) # 👉️ -11 print(int(-13.9)) # 👉️ -13
Notice that there is a difference to how math.floor()
and int()
handle
negative numbers:
math.floor()
rounds towards negative infinityint()
truncates towards zeroAlternatively, you can use the math.trunc()
method.
Use the math.trunc()
method to round a float down to the nearest integer,
e.g. result = math.trunc(3.999)
. The math.trunc()
method removes the
fractional part and returns the integer part of the given number.
import math result_1 = math.trunc(3.999) print(result_1) # 👉️ 3 result_2 = math.trunc(3.14) print(result_2) # 👉️ 3 result_3 = math.trunc(-3.6) print(result_3) # 👉️ -3
The math.trunc method takes a number, removes its fractional part and returns its integer part.
The math.trunc()
method rounds towards zero.
import math print(math.trunc(-9.1)) # 👉️ -9 print(math.trunc(-9.9)) # 👉️ -9
This approach achieves the same result as passing the floating-point number to
the int()
class.