如何使用 Python 字符串格式将表示美分的整数转换为表示美元的浮点数? [英] How to use Python string formatting to convert an integer representing cents to a float representing dollars?

查看:28
本文介绍了如何使用 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

我应该提供一些背景知识.我将价格作为整数存储在数据库中,以确保不会丢失精度.我不想使用 Decimal 数据类型,因为这些值也将用于 Javascript 中的计算,因此整数将最容易使用.我希望能够使用 stringformat 标记在 Django 模板中显示格式化的值.因此,将数字除以 100 不起作用.有没有除法加小数点的方法?

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?

推荐答案

您应该尽量避免使用浮点数来表示金钱(数字不准确很容易出现).十进制模块提供了一种有用的数据类型来表示货币,因为它可以精确地表示十进制数,例如 0.05.

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.

可以这样使用:

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

这篇关于如何使用 Python 字符串格式将表示美分的整数转换为表示美元的浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆