我有一美元的价格作为具有.01
精度的Decimal
字符串格式化在Python:显示价格不带小数点的
我想在字符串格式化以显示它,就像有一个消息(到分)。 "You have just bought an item that cost $54.12."
事情是,如果价格恰好是圆的,我想只显示它没有美分,如$54
。
如何在Python中完成此操作?请注意,我使用Python 2.7,所以我很乐意使用新风格而不是旧风格的字符串格式。
我有一美元的价格作为具有.01
精度的Decimal
字符串格式化在Python:显示价格不带小数点的
我想在字符串格式化以显示它,就像有一个消息(到分)。 "You have just bought an item that cost $54.12."
事情是,如果价格恰好是圆的,我想只显示它没有美分,如$54
。
如何在Python中完成此操作?请注意,我使用Python 2.7,所以我很乐意使用新风格而不是旧风格的字符串格式。
我会做这样的事情:
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
我不认为这就是他想要的。他希望'$ 54.12'作为输出。只有当值是'54.00'时,他希望小数点被切掉。 – 2012-03-04 18:22:12
什么优势增加了“小数”模块?这似乎没用。 – Zenon 2012-03-04 18:23:34
@ Zeen:from [the documentation](http://docs.python.org/library/decimal.html):“与基于硬件的二进制浮点不同,'decimal'模块具有用户可更改的精度(默认为28个地方),对于一个特定的问题,这个地方可以像需要的那样大。“ – bernie 2012-03-04 18:28:31
>>> import decimal
>>> n = decimal.Decimal('54.12')
>>> print('%g' % n)
'54.12'
>>> n = decimal.Decimal('54.00')
>>> print('%g' % n)
'54'
它使用'decimal.getcontext()。prec = 2' ... – ezod 2012-03-04 18:40:32
@DavidHall:嗨,你说得对。抱歉。我会收回我以前的评论。有趣的是,新的格式化语言不能这样工作:'“{0:g}”.format(decimal.Decimal(“54.00”))'返回'54.00'! – 2012-03-04 18:43:38
你说得对,我的错。 – 2012-03-04 18:43:55
>>> 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.
我已经得到了'十进制'的值,我不硬编码它... – 2012-03-04 18:41:02
这是你想要什么项目?
备注:x
是原始价格。
round = x + 0.5
s = str(round)
dot = s.find('.')
print(s[ : dot])
这是一个算法。我不想要算法。我想使用Python的内置系统。如果不可能,我会使用算法。 – 2012-03-04 18:42:04
>>> a=54.12
>>> x="${:.4g}".format(a)
>>> print x
$54.12
>>> a=54.00
>>> x="${:.4g}".format(a)
>>> print x
$54
答案取自http://stackoverflow.com/questions/2389846/python-decimals-format – redratear 2016-08-02 09:12:08
看看这个答案取自[删除尾随零在Python(http://stackoverflow.com/a/5808014/63011) – 2012-03-04 18:29:20
@PaoloMoretti:我不会想要一个算法。我想使用Python的内置系统。如果不可能的话,我会制作我自己的算法。 – 2012-03-04 18:39:40