askvity

How to round down to the nearest whole number in Python?

Published in Rounding Numbers 2 mins read

To round down to the nearest whole number (integer) in Python, you can use the math.floor() method.

Using math.floor()

The math.floor() function is part of Python's math module. It takes a number as input and returns the largest integer less than or equal to that number. In simpler terms, it rounds the number down to the nearest whole number.

import math

number = 3.7
rounded_down = math.floor(number)
print(rounded_down)  # Output: 3

number = -2.3
rounded_down = math.floor(number)
print(rounded_down)  # Output: -3

As you can see from the examples, math.floor() consistently rounds down, even for negative numbers.

Quick Reference Table

Method Description Example Result
math.floor() Rounds a number down to the nearest integer. math.floor(3.7) 3
math.floor() Rounds a number down to the nearest integer, including negatives. math.floor(-2.3) -3

Example Scenarios

Here are a couple more examples to illustrate practical use cases:

  • Calculating the number of full weeks: Suppose you have a number of days and want to calculate how many full weeks those days represent.

    import math
    days = 17
    weeks = math.floor(days / 7)
    print(weeks) # Output: 2
  • Converting meters to the largest possible whole number of kilometers:

    import math
    meters = 3456
    kilometers = math.floor(meters / 1000)
    print(kilometers) # Output: 3

In summary, math.floor() is the go-to method for rounding down to the nearest integer in Python. Remember to import the math module before using it. If you need to round up, consider using math.ceil() as noted in the reference information.

Related Articles