Borislav Hadzhiev
Last updated: Jul 12, 2022
Check out my new book
To round a list of floats into integers:
round()
function.list_of_floats = [2.4, 3.5, 6.7, 8.1] new_list = [round(item) for item in list_of_floats] # 👇️ [2, 4, 7, 8] print(new_list)
We used a list comprehension to iterate over the list of floats.
On each iteration, we pass the current list element to the round()
function to
round it to the nearest integer.
The round function takes the following 2 parameters:
Name | Description |
---|---|
number | the number to round to ndigits precision after the decimal |
ndigits | the number of digits after the decimal, the number should have after the operation (optional) |
The round
function returns the number rounded to ndigits
precision after the
decimal point.
ndigits
is omitted, the function returns the nearest integer.fav_num = 3.456 result1 = round(fav_num) print(result1) # 👉️ 3 result2 = round(fav_num, 2) print(result2) # 👉️ 3.46
Alternatively, you can use the map()
function.
To round a list of floats into integers:
round()
function and the list to the map()
function.map()
function will pass each float to the round()
function.list()
class to convert the map
object to a list.list_of_floats = [2.4, 3.5, 6.7, 8.1] new_list = list(map(round, list_of_floats)) # 👇️ [2, 4, 7, 8] print(new_list)
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
map()
function calls the round()
function will each floating-point number in the list and rounds each value.The last step is to use the list()
class to convert the map
object to a
list.
The list class takes an iterable and returns a list object.
Which approach you pick is a matter of personal preference. I'd go with the list comprehension as I find it more direct and easier to read.