Why wont variables in the list print to 3 decimal places?

56 views Asked by At

When I make the first parameter less than three decimal places and try make it be converted to three decimal places it won't do it. It will just add it to the list how I wrote it. If the value is 9.13, it won't print in the list as 9.130, it will still be 9.13. I've tried the round function, formatting, etc. Also, when an integer is added to the list it will only print to one decimal place. For example, 27 will only print 27.0 instead of 27.000.

import math

def generate_num(LowNum, HighNum):
    
    try:
        LowNum = float(LowNum)
        HighNum = float(HighNum)

    except ValueError:
        return False
    except KeyboardInterrupt:
        quit()

    LowNum = round(LowNum, 3)
    sequence = [LowNum]
    j = sequence[-1]

    while j <= HighNum:
        i = (math.sqrt((j) ** 3))
        i = round(i, 3)

        if i <= HighNum:
            sequence.append(i)
            j = i  
        else:
            break

    return sequence


print(generate_num(9, 923))
2

There are 2 answers

2
Svenito On

The function round() does not determine the format when a list is printed out. It just rounds the number to three decimal places. 9.13 rounded to 3 places just stays 9.13. If I understand you correctly, you want the numbers to be formatted all with exactly 3 decimal places. For that you would have to use some kind of string format expression. For example you could use this instead of print():

for num in generate_num(9,923):
    print(f'{num:.3f}')

Depending on your preference you could print the like a list if you print the brackets and the commas manually also.

0
Mark Tolonen On

round() changes the value of the number. Formatting controls the display:

>>> n = 3.00256
>>> n
3.00256
>>> m = round(n,3)  # Make a new rounded number
>>> m
3.003
>>> n
3.00256
>>> m==n
False
>>> m = round(n,2)
>>> m
3.0
>>> n
3.00256
>>> m==n
False
>>> print(f'{n:.3f}')  # Display to 3 places
3.003
>>> print(f'{n:.2f}')  # Display to 2 places
3.00
>>> n                  # n is unchanged
3.00256

If you want a custom display of a list, you have to do it yourself:

>>> def display(L):
...   print('['+', '.join([f'{n:.3f}' for n in L]) + ']')
...
>>> L = [1.1, 2.22, 3.333, 4.4444, 5.5555]
>>> L
[1.1, 2.22, 3.333, 4.4444, 5.5555]
>>> display(L)
[1.100, 2.220, 3.333, 4.444, 5.556]