[Python] Formatting a list of floats to 2 Decimal Points

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to search though text to find Money EG £12.30 take the numbers and then sum them.I have managed to get to the point where I have a list of floats but I can't seem to get them to 2 decimal points. However like in the code below if I specify an element in the list like [0] for example then it formats that element to 2 decimal points.

    So my question would be: How can I format the whole list to 2 decimal places bearing in mind I will have no idea how long the list will be.

    import re

    num_regex = re.compile(r'\d\d.\d\d')
    file_name = input("Enter File Name to open: ")

    text_file = open(file_name, 'r')
    search_text = text_file.read()
    search = num_regex.findall(search_text)
    print("Numbers found:", search,)
    new_search =[]
    for item in search:
    new_search.append(float(item))
    new_search[0] = "%.2f" % new_search[0]
    print(new_search[0])

    Continue reading...

Compartilhe esta Página