How to use Python string formatting to convert an integer representing cents to a float representing dollars?

房东的猫 提交于 2019-11-27 06:20:24

问题


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? 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. I want to be able to display in a Django template the formatted value using the stringformat tag. As such, dividing the number by 100 doesn't work. Is there a way to add the decimal point without dividing?


回答1:


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.

It can be used like this:

import decimal
cents = 999
dollars = decimal.Decimal(cents) / 100
print dollars



回答2:


If you don't care about localization, then simply divide by 100 and format it:

>>> 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:

>>> 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'



回答3:


Using 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}'.



来源:https://stackoverflow.com/questions/8637628/how-to-use-python-string-formatting-to-convert-an-integer-representing-cents-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!