daniel
daniel

Reputation: 1978

decimal.Decimal(float) vs. decimal.Decimal.from_float(float)

I'm a newbie in Python programming and lately I've been learning some aspects of data types. As I read, the method decimal.Decimal() creates a decimal object; decimal.Decimal.from_float() method creates a decimal object from a float object. However, both produce the same output:

>>> import decimal
>>> x = 3.14561
>>> y = 3.14561
>>> x = decimal.Decimal.from_float(x)
>>> y = decimal.Decimal(y)
>>> x == y

True

So, what is the difference between the two?

Upvotes: 2

Views: 912

Answers (2)

Enrico Granata
Enrico Granata

Reputation: 3339

Looking at the docs, before Python 2.7 the Decimal() constructor could not take a float argument, which is why you needed the from_float() class method

Starting with 2.7, the constructor can also take a float directly, so the two are the same.

Still from the docs, I suppose the reason why constructing from float was initially disallowed is that:

Note Decimal.from_float(0.1) is not the same as Decimal(‘0.1’). Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4. That equivalent value in decimal is 0.1000000000000000055511151231257827021181583404541015625.

Upvotes: 3

Adam Smith
Adam Smith

Reputation: 54243

per the Python3 Docs,

Note: From Python 2.7 onwards, a Decimal instance can also be constructed directly from a float.

So as long as you're running Python 2.7+, nothing.

Upvotes: 1

Related Questions