Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

django templates - 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? 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...