python里美元怎么表示,如何使用Python字符串格式将代表美分的整数转换为代表美元的浮点数?...

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?

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值