Python Decimal to String Python Decimal to String python python

Python Decimal to String


Use the str() builtin, which:

Returns a string containing a nicely printable representation of an object.

E.g:

>>> import decimal>>> dec = decimal.Decimal('10.0')>>> str(dec)'10.0'


Use the string format function:

>>> from decimal import Decimal>>> d = Decimal("0.0000000000000123123")>>> s = '{0:f}'.format(d)>>> print(s)0.0000000000000123123

If you just type cast the number to a string it won't work for exponents:

>>> str(d)'1.23123E-14' 


Note that using the %f string formatting appears to either convert to a float first (or only output a limited number of decimal places) and therefore looses precision. You should use %s or str() to display the full value stored in the Decimal.

Given:

from decimal import Decimalfoo = Decimal("23380.06198573179271708683473")print("{0:f}".format(foo))print("%s" % foo)print("%f" % foo)

Outputs:

23380.0619857317927170868347323380.0619857317927170868347323380.061986

(ed: updated to reflect @Mark's comment.)