Python Forum
Controlling trailing zeros with rounding? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Controlling trailing zeros with rounding? (/thread-7788.html)



Controlling trailing zeros with rounding? - RedSkeleton007 - Jan-25-2018

I'm trying to print out floats in currency format, but no matter what numbers I specify for rounding parameters, it only prints out one 0 after the decimal point:
#!/usr/bin/env python3
#FormattingStuff.py

def listOfFloats():
    floatsList = [20.0007, 20.00, 3.00, 5.780001]
    print("$" + str(round(floatsList[1], 2)))
    print("$" + str(round(floatsList[1], 3)))

def main():
    listOfFloats()

main()
The output is:
Error:
======= RESTART: I:/Python/Python36-32/SamsPrograms/FormattingStuff.py ======= $20.0 $20.0 >>>
Why are they the same? I'm trying to output $20.00


RE: Controlling trailing zeros with rounding? - j.crater - Jan-25-2018

round is doing the rouding mathematically, so if last decimal(s) is zero(es) it will omit them from printing. Try with the format method instead:
print('${:.2f}'.format(round(floatsList[1], 2)))