round a number to the nearest integer in python

You can use the built-in round() function in Python to round a number to the nearest integer.

main.py
num = 3.6
rounded_num = round(num)
print(rounded_num) # Output: 4
66 chars
4 lines

The round() function can also be used to round a number to a specified number of decimal places.

main.py
num = 3.14159
rounded_num = round(num, 2)
print(rounded_num) # Output: 3.14
76 chars
4 lines

Alternatively, you can use the math module and its floor() or ceil() functions to round down or up to the nearest integer, respectively.

main.py
import math

num = 3.6
floor_num = math.floor(num)
ceil_num = math.ceil(num)

print(floor_num) # Output: 3
print(ceil_num) # Output: 4
135 chars
9 lines

Note that both floor() and ceil() functions return a float value. You can convert the result to an integer using the built-in int() function if needed.

gistlibby LogSnag