NoWaterNoKoolAid
NoWaterNoKoolAid

Reputation: 1

format a string using .format() to convert a float into dollars and cents left justified in python

I am trying to use .format() to convert a float into a dollar amount. I have accomplished that task, however, I have a major problem. I get empty spaces in between the dollar sign and the value. Is there a way for me to have the field length (width of the field) constant and have the "$" next to the number, regardless of the numbers length?

This is what I have tried:

Screenshot of my console

money = 1243432.6
  1. '${:>,.2f}'.format(money)
    Output: '$1,243,432.60'

  2. '${:>10,.2f}'.format(money)
    Output:'$ 1,243,432.60'

  3. '${:>20,.2f}'.format(money)
    Output:'$ 1,243,432.60'

Upvotes: 0

Views: 1111

Answers (2)

pafreire
pafreire

Reputation: 146

You can do this using str.format() method as below:

float_ = 1976.25
print('${:.2f}'.format(float_))

The parameter .2f forces format method to show only two decimals after the point.

You could show the commas representing thousands with a little change:

print('${:,.2f}'.format(float_))

Upvotes: 2

pault
pault

Reputation: 43504

Here's an example that you may find helpful.

amounts = [1.234, 20.3, 100.19999]
for a in amounts:
    print("${:0.2f}".format(a))
#$1.23
#$20.30
#$100.20

More information on the format specification can be found here in the docs.

Upvotes: 0

Related Questions