Search code examples
pythonfloating-pointtabular

Number formatting not working with tabulate after printing text


I'm writing this little program learning Python and I have faced a problem. I use tabulate with number formatting set to 5 numbers after separator, to make everything look nice, and it works, until I print text in the table. After text is printed (stating that you cannot divide by 0), formatting on that column seems to be gone.

The code is:

if skaiciuoti == True:
while bp <= bg:
    if (bp-a != 0):
        y = float(a / (bp - a))
        sk1.append(a)
        sk2.append(bp)
        sk3.append(y)
        bp = bp + bz
    elif (bp - a == 0):
        sk1.append(a)
        sk2.append(bp)
        sk3.append('Veiksmas negalimas (dalyba is 0)')
        bp = bp + bz

lentele = ['A reiksme', 'B reiksme', 'Y reiksme']
duomenys = zip(sk1, sk2, sk3)

print(tabulate (duomenys, headers=lentele, floatfmt=".5f", tablefmt="grid"))

Here are pictures to better illustrate my problem:

Working one

Broken one

I have tried formatting the number before appending it to the list, but it didn't work.

Any suggestions and ideas are welcome.


Solution

  • Okay, I've managed to fix it myself. It was really not that hard, I just didn't think about it.

    The solution that worked for me was to format number when appending it to the list (not before the list) like so

    sk3.append(format(y, '.5f'))