Python string formatting: displaying prices without decimal points

I have the price of the Dollar as Decimalaccurate .01(to the cent.)

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

The fact is that if the price is round, I want to just show it without a cent, for example $54.

How can I accomplish this in Python? Please note that I am using Python 2.7, so I would be happy to use string formatting in the new style, rather than the old style.

+5
source share
5 answers

I would 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))

{0:.{1}f} float, , 0, 2, , , , .

:

$54,12.

$54

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

The answer is taken from Python decimal format

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

Is this what you want?

Note : x- This is the original price.

round = x + 0.5
s = str(round)
dot = s.find('.')
print(s[ : dot])
0
source
>>> 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.
-1
source

All Articles