Python Decimal to String

会有一股神秘感。 提交于 2019-12-20 10:17:56

问题


There are tons of topics on here that explain how to convert a string to a decimal, but how do I convert a decimal back to a string?

Like if I did this:

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

How would I take dec and get '10.0' (a string) out?


回答1:


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'



回答2:


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' 



回答3:


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



回答4:


Almost all the built-ins work on the Decimal class as you would expect:

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

A string:

>>> str(dec)
'10.0'

A float:

>>> float(dec)
10.0

An int:

>>> int(dec)
10

Object representation (as it would be in the interactive interpreter):

>>> repr(dec)
"Decimal('10.0')"

Rational number:

>>> import fractions
>>> fractions.Fraction(decimal.Decimal('0.50'))
Fraction(1, 2)



回答5:


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 Decimal
foo = Decimal("23380.06198573179271708683473")
print("{0:f}".format(foo))
print("%s" % foo)
print("%f" % foo)

Outputs:

23380.06198573179271708683473
23380.06198573179271708683473
23380.061986

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



来源:https://stackoverflow.com/questions/11093021/python-decimal-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!