Laetitia Bracco
Laetitia Bracco

Reputation: 19

How do I convert a list of floats into a list of percentages?

I have this list :

list = [
  0.6490486257928119,
  0.2996742671009772,
  0.589242053789731
]

I would like to convert it into a list of percentages with one decimal, like this :

list = [
  64.9%,
  29.9%,
  58.9%
]

I don't know how to proceed. 

Upvotes: 1

Views: 5567

Answers (3)

RapThor
RapThor

Reputation: 36

print("{0:.1f}%".format(0.6490486257928119*100))

Part 1:

"{0:.1f}%"

This is the "done format section" the percentage symbol, it doesn't needs explanation... {in here} the formatted text is placed here '0' (zero) is the index of the integer, what we want to format. In here is the 0.649048...x100 . The ".1" specifies the location of the decimal point and the "f" is for the float

Part 2:

.format(0.6490486257928119*100)

And in the end of the .format() function where we give the integer, or double, or float

REALLY REALLY SORRY FOR MY ENGLISH!!!

Upvotes: 1

Albert H M
Albert H M

Reputation: 266

You could do that with list comprehension. For example :

list = [0.6490486257928119, 0.2996742671009772, 0.589242053789731]

new_list = [ round(x*100,1) for x in list] #each value in list multiplied by 100 and round up to 1 floating number

new_list = [64.9, 29.9, 58.9]

if u want to have %, u can convert to string

new_list = [ str(round(x*100,1))+"%" for x in list]

new_list = ["64.9%", "29.9%", "58.9%"]

Upvotes: 1

mapf
mapf

Reputation: 2058

You could use list comprehension. Be aware however, that the result you would like changes the type of the items from float to str because of the percentage symbol that you would like to include.

As a side note: you shouldn't use list as your variable name because that way, you are overwriting Pythons list method.

lst = [0.6490486257928119, 0.2996742671009772, 0.589242053789731]

new_lst = [f'{i*100:.1f}%' for i in lst]

print(new_lst)

Upvotes: 3

Related Questions