[英]How to use Python string formatting to convert an integer representing cents to a float representing dollars?
I have an integer representing a price in cents. 我有一个整数表示以美分为单位的价格。 Using Python format strings, how can I convert this value into dollars with two decimal places?
使用Python格式字符串,如何将此值转换为带有两位小数的美元? Examples:
例子:
1234 => 12.34
5 => 0.05
999 => 9.99
EDIT: I should give some background. 编辑:我应该给一些背景知识。 I am storing prices in a database as integers in order to make sure I don't loose precision.
我将价格存储在数据库中作为整数,以确保我不会失去精度。 I don't want to use the Decimal datatype because these values will also be used in calculations in Javascript, so integers will be simplest to work with for that.
我不想使用Decimal数据类型,因为这些值也将用于Javascript中的计算,因此整数最简单。 I want to be able to display in a Django template the formatted value using the stringformat tag.
我希望能够使用stringformat标签在Django模板中显示格式化的值。 As such, dividing the number by 100 doesn't work.
因此,将数字除以100不起作用。 Is there a way to add the decimal point without dividing?
有没有办法添加小数点而不分割?
You should try hard to avoid ever using floats to represent money (numerical inaccuracy can too easily creep in). 你应该尽量避免使用花车来代表金钱(数字不准确可能太容易蔓延)。 The decimal module provides a useful datatype for representing money as it can exactly represent decimal numbers such as 0.05.
十进制模块提供了一种有用的数据类型来表示货币,因为它可以精确地表示十进制数,例如0.05。
It can be used like this: 它可以像这样使用:
import decimal
cents = 999
dollars = decimal.Decimal(cents) / 100
print dollars
If you don't care about localization, then simply divide by 100 and format it: 如果你不关心本地化,那么简单地除以100并格式化它:
>>> for cents in [ 1234, 5, 999 ]:
... '{0:.02f}'.format(float(cents) / 100.0)
...
'12.34'
'0.05'
'9.99'
If you do care about localization, then use the locale
module: 如果您关心本地化,请使用
locale
模块:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, "") # use the user-default locale
'en_US.UTF-8'
>>> for cents in [ 1234, 5, 999 ]:
... locale.currency(float(cents) / 100.0)
...
'$12.34'
'$0.05'
'$9.99'
Using str.format : 使用str.format :
for i in (1234,5,999):
print('{:.2f}'.format(i/100.))
yields 产量
12.34
0.05
9.99
In Python2.6 use '{0:.2f}'
instead of '{:.2f}'
. 在Python2.6中使用
'{0:.2f}'
而不是'{:.2f}'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.