Python float to Decimal conversion

Python float to Decimal conversion

Python <2.7

%.15g % f

Or in Python 3.0:

format(f, .15g)

Python 2.7+, 3.2+

Just pass the float to Decimal constructor directly, like this:

from decimal import Decimal

You said in your question:

Can someone suggest a good way to
convert from float to Decimal
preserving value as the user has

But every time the user enters a value, it is entered as a string, not as a float. You are converting it to a float somewhere. Convert it to a Decimal directly instead and no precision will be lost.

Python float to Decimal conversion

I suggest this

>>> a = 2.111111
>>> a
>>> str(a)
>>> decimal.Decimal(str(a))

Leave a Reply

Your email address will not be published. Required fields are marked *