Python Forum

Full Version: Controlling trailing zeros with rounding?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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)))