[Python] How can I convert a list of numbers in various decimals to two decimal places...

Discussão em 'Python' iniciado por Stack, Abril 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have a code that calculate the growth of population as follows:

    new_pop = init_pop
    new_pop_list = [new_pop]
    while new_pop <= 1500:
    new_pop *= (1 + growth_rate)
    new_pop_list.append(round(new_pop, 2))

    print(new_pop_list)


    which displays a list of number in various decimals

    [1000, 1050.0, 1102.5, 1157.62, 1215.51, 1276.28, 1340.1, 1407.1, 1477.46, 1551.33]


    How can I display the above list with all number in 2 decimal places, that is

    [1000.00, 1050.000, 1102.50, 1157.62, 1215.51, 1276.28, 1340.10, 1407.10, 1477.46, 1551.33]


    If I tried

    new_pop_list.append(format(new_pop, '.2f'))


    The output would be displayed as string instead of number, that is

    ['1000.00', '1050.000', ..., '1407.10', '1477.46', '1551.33']


    Using float after format didn't do the trick either (numbers in various decimal scales)

    new_pop_list.append(float(format(new_pop, '.2f')))
    # Output displayed as [1000, 1050.0, 1102.5, 1157.62, 1215.51, 1276.28, 1340.1, 1407.1, 1477.46, 1551.33]

    Continue reading...

Compartilhe esta Página