Python Forum
Controlling trailing zeros with rounding?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Controlling trailing zeros with rounding?
#1
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
Reply
#2
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)))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Controlling program with TCP commands lavacode 1 518 Jul-10-2023, 04:39 PM
Last Post: deanhystad
  need help rounding joseph202020 7 1,257 Feb-21-2023, 08:13 PM
Last Post: joseph202020
  from numpy array to csv - rounding SchroedingersLion 6 2,063 Nov-14-2022, 09:09 PM
Last Post: deanhystad
  Removing leading\trailing spaces azizrasul 8 2,530 Oct-23-2022, 11:06 PM
Last Post: azizrasul
  Controlling text-to-speech pauses with pyttsx3 pmac1300 4 4,321 Mar-14-2022, 06:47 AM
Last Post: Coricoco_fr
  remove zeros at the end of a number Frankduc 7 2,102 Feb-25-2022, 03:48 PM
Last Post: Frankduc
  Controlling what get outputted to stdout when running external commands Daring_T 4 2,111 Jan-30-2022, 05:40 PM
Last Post: bowlofred
  Random data generation sum to 1 by rounding juniorcoder 9 3,347 Oct-20-2021, 03:36 PM
Last Post: deanhystad
  Rounding issue kmll 1 1,379 Oct-08-2021, 10:35 AM
Last Post: Yoriz
  Solving for zeros of an equation! fmitchell17 0 1,803 Apr-05-2021, 07:49 PM
Last Post: fmitchell17

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020