Ram Rachum
Ram Rachum

Reputation: 88598

String formatting in Python: Showing a price without decimal points

I have a Dollar price as a Decimal with a precision of .01 (to the cent.)

I want to display it in string formatting, like having a message "You have just bought an item that cost $54.12."

The thing is, if the price happens to be round, I want to just show it without the cents, like $54.

How can I accomplish this in Python? Note that I'm using Python 2.7, so I'd be happy to use new-style rather than old-style string formatting.

Upvotes: 6

Views: 5657

Answers (5)

redratear
redratear

Reputation: 249

Answer is taken from Python Decimals format

>>> a=54.12
>>> x="${:.4g}".format(a)
>>> print x
   $54.12
>>> a=54.00
>>> x="${:.4g}".format(a)
>>> print x
   $54

Upvotes: 2

Autumn K.
Autumn K.

Reputation: 33

Is this what you want?

Note: x is the original price.

round = x + 0.5
s = str(round)
dot = s.find('.')
print(s[ : dot])

Upvotes: 0

ezod
ezod

Reputation: 7421

>>> import decimal
>>> n = decimal.Decimal('54.12') 
>>> print('%g' % n)
'54.12'
>>> n = decimal.Decimal('54.00') 
>>> print('%g' % n)
'54'

Upvotes: 6

jcollado
jcollado

Reputation: 40394

I'd do something like this:

import decimal

a = decimal.Decimal('54.12')
b = decimal.Decimal('54.00')

for n in (a, b):
    print("You have just bought an item that cost ${0:.{1}f}."
          .format(n, 0 if n == n.to_integral() else 2))

where {0:.{1}f} means print the first argument as a float using the number of decimals in the second argument and the second argument is 0 when the number is actually equal to its integer version and 2 when is not which I believe is what you're looking for.

The output is:

You have just bought an item that cost $54.12.

You have just bought an item that cost $54

Upvotes: 1

Fred
Fred

Reputation: 1021

>>> dollars = Decimal(repr(54.12))
>>> print "You have just bought an item that cost ${}.".format(dollars)
You have just bought an item that cost $54.12.

Upvotes: -1

Related Questions