I want to represent money which is usually to 2DP and I add up items using float values but whenever I have a value that is similar to the one used it only converts it to a string to 1DP.

This seems like its going to be annoying to work around. I'm thinking of using a regular expression and an if statement to add a "0" to the end if the string is only to 1DP but i was wondering if there were any other methods I could use.

Any ideas?

number = 0.60

string = "0.60"

stringofnumber = str(number)

print number

print string

print stringofnumber

Recommended Answers

All 2 Replies

Something you can look at,for doing financial calculations look at Decimal module.
http://docs.python.org/library/decimal.html

>>> number = 0.60
>>> print '%.2f' % number
0.60

>>> from decimal import *
>>> Decimal('0.60')
Decimal('0.60')
>>> Decimal('0.60') + Decimal('0.60')
Decimal('1.20')
>>> 
>>> print Decimal('0.60') + Decimal('0.60')
1.20
commented: This post was concise and to the point with good examples +2

Thanks that's a lot more convenient to be honest.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.