2012-03-04 63 views
5

我有一美元的價格作爲具有.01精度的Decimal字符串格式化在Python:顯示價格不帶小數點的

我想在字符串格式化以顯示它,就像有一個消息(到分)。 "You have just bought an item that cost $54.12."

事情是,如果價格恰好是圓的,我想只顯示它沒有美分,如$54

如何在Python中完成此操作?請注意,我使用Python 2.7,所以我很樂意使用新風格而不是舊風格的字符串格式。

+0

看看這個答案取自[刪除尾隨零在Python(http://stackoverflow.com/a/5808014/63011) – 2012-03-04 18:29:20

+0

@PaoloMoretti:我不會想要一個算法。我想使用Python的內置系統。如果不可能的話,我會製作我自己的算法。 – 2012-03-04 18:39:40

回答

1

我會做這樣的事情:

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}手段打印的第一個參數爲使用小數的第二個參數和數量,第二個參數的浮動是0當數實際上等於到它的整數版本和2當不是我相信是你正在尋找。

輸出是:

你剛纔買了花費$ 54.12的項目。

你剛纔買了花費$ 54

+4

我不認爲這就是他想要的。他希望'$ 54.12'作爲輸出。只有當值是'54.00'時,他希望小數點被切掉。 – 2012-03-04 18:22:12

+0

什麼優勢增加了「小數」模塊?這似乎沒用。 – Zenon 2012-03-04 18:23:34

+2

@ Zeen:from [the documentation](http://docs.python.org/library/decimal.html):「與基於硬件的二進制浮點不同,'decimal'模塊具有用戶可更改的精度(默認爲28個地方),對於一個特定的問題,這個地方可以像需要的那樣大。「 – bernie 2012-03-04 18:28:31

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

它使用'decimal.getcontext()。prec = 2' ... – ezod 2012-03-04 18:40:32

+0

@DavidHall:嗨,你說得對。抱歉。我會收回我以前的評論。有趣的是,新的格式化語言不能這樣工作:'「{0:g}」.format(decimal.Decimal(「54.00」))'返回'54.00'! – 2012-03-04 18:43:38

+0

你說得對,我的錯。 – 2012-03-04 18:43:55

-1
>>> 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. 
+0

我已經得到了'十進制'的值,我不硬編碼它... – 2012-03-04 18:41:02

0

這是你想要什麼項目?

備註x是原始價格。

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

這是一個算法。我不想要算法。我想使用Python的內置系統。如果不可能,我會使用算法。 – 2012-03-04 18:42:04

1

的回答是從Python Decimals format

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

答案取自http://stackoverflow.com/questions/2389846/python-decimals-format – redratear 2016-08-02 09:12:08