Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 869
Ram Rachum Avatar asked Mar 04 '12 18:03

Ram Rachum


1 Answers

>>> import decimal
>>> n = decimal.Decimal('54.12') 
>>> print('%g' % n)
'54.12'
>>> n = decimal.Decimal('54.00') 
>>> print('%g' % n)
'54'
like image 186
ezod Avatar answered Sep 28 '22 06:09

ezod