Friday, October 2, 2009

Django - Cannot convert float to Decimal

Ever see one of these?

Exception Type: TypeError
Exception Value:

Cannot convert float to Decimal. First convert the float to a string

This is caused by the fact that python cannot convert a float to a decimal. It is a feature of python, not a bug. The essence of the issue is that a float is a representation of a decimal number from binary. You don't really know what's exactly stored in a float, only that it is within some very close distance to the number you
want to be there. For example a float variable x assigned the value 24 might actually contain the value 24.000000000001. The variable x is close enough to 24 for most applications that you wouldn't mind the small discrepancy. A decimal variable, however, is an exact value. If you set decimal variable x to 24 then it is exactly 24. Converting a float to a decimal requires guesswork. Python's design philosophy seeks to avoid making guesses. Thus the programmer must handle that conversion explicitly.

I encountered this problem when importing a float value from the settings file.

import settings
from decimal import *

foo = Decimal(str(settings.FOO))
# foo will now work with django decimal model fields.

No comments:

Post a Comment