Python 2.7 issue with decimal value 0.0
Tim Golden
mail at timgolden.me.uk
Wed Mar 25 10:37:51 EDT 2015
On 25/03/2015 14:29, Oscar Benjamin wrote:
> On 25 March 2015 at 14:20, Larry Martell <larry.martell at gmail.com> wrote:
>> I have an app that works with 2.6, but in 2.7 it is failing. I traced
>> it down to an issue with decimal.Decimal being passed a value of 0.0.
>> It 2.6 this is fine, but in 2.7 it throws an exception:
>>
>> TypeError: Cannot convert float to Decimal. First convert the float to a string
>>
>> This is easy enough to deal with, but I find it odd. Is this a known issue?
>
> Perhaps I've misunderstood but decimal.Decimal(0.0) works fine here:
>
> $ python2.7
> Python 2.7.3 (default, Dec 18 2014, 19:10:20)
> [GCC 4.6.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import decimal
>>>> decimal.Decimal(0.0)
> Decimal('0')
I suspect the OP is confusing himself a little: the ability to create a
Decimal object directly from a float/int was added in 2.7. In 2.6 you
have to create it from a string (and if you don't you get the very error
message he posts above).
<dump>
ActivePython 2.6.6.18 (ActiveState Software Inc.) based on
Python 2.6.6 (r266:84292, Jan 7 2011, 13:16:36) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import decimal
>>> decimal.Decimal(0.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\python26\lib\decimal.py", line 649, in __new__
"First convert the float to a string")
TypeError: Cannot convert float to Decimal. First convert the float to
a string
>>>
</dump>
TJG
More information about the Python-list
mailing list