1

Hi so i'm currently trying to write a code that asks for a number of days and then opens multiple text files(temps1.txt etc), reads them, sorts them into dictionarys with an average and then prints it out. However some of the averages have an extreme amount of decimal spots

f = {}
ans = int(input('How many days of data do you have? '))
#figure out how to open certain files
for file_num in range(1, (ans+1)):
    file_name = "temps" + str(file_num) + ".txt"
    temps = open(file_name)
    for line in temps:
        room, num = line.strip('\n').split(',')
        num = int(num)
        #may need to be 4* however many times it appears
        num = num/(4*ans)
        f[room] = f.get(room, 0) + num

print('Average Temperatures:')
for x in f:
     print (x + ':',f[x])

i have an example for a room called bedroom (all the bedrooms in the text files average) and the average is 26.0 however it prints out as 26.000000000000004 how do i stop it doing this?

  • 1
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Amadan Aug 30 '18 at 04:27
  • Dividing each then adding is less precise than adding then dividing the sum. – Amadan Aug 30 '18 at 04:28

3 Answers3

2

You can tell Python how to format the number like this:

print('Average Temperatures:')
for x in f:
     print ('%.1f:' % x, f[x])

The %.1f says to print as a floating point number, with 1 number after the decimal point.

Brian Bienvenu
  • 349
  • 1
  • 11
0

Check out the 'round()' function. Check out: How to round down to 2 decimals with Python?

>>> x = 26.000000000000004
>>> print str(round(x, 2))  
>>> '26.00'
0

You can use:

for x in f:
    print("{:.2f}".format(float(x)))

.2f means 2 digits after dot. See https://docs.python.org/3.7/library/string.html#formatstrings for more options.

nauer
  • 690
  • 5
  • 14