gfr*_*ng4 37 python string decimal
这里有很多主题可以解释如何将字符串转换为小数,但是如何将小数转换回字符串?
就像我这样做:
import decimal
dec = decimal.Decimal('10.0')
Run Code Online (Sandbox Code Playgroud)
我怎么拿出dec来'10.0'(一根绳子)?
Gar*_*tty 51
使用了str()内置的,其中:
返回包含对象的可打印表示的字符串.
例如:
>>> import decimal
>>> dec = decimal.Decimal('10.0')
>>> str(dec)
'10.0'
Run Code Online (Sandbox Code Playgroud)
Mat*_*rts 28
使用字符串格式函数:
>>> from decimal import Decimal
>>> d = Decimal("0.0000000000000123123")
>>> s = '{0:f}'.format(d)
>>> print(s)
0.0000000000000123123
Run Code Online (Sandbox Code Playgroud)
如果您只是将数字类型转换为字符串,则它将不适用于指数:
>>> str(d)
'1.23123E-14'
Run Code Online (Sandbox Code Playgroud)
请注意,使用%f字符串格式似乎首先转换为浮点数(或仅输出有限数量的小数位),因此会降低精度。您应该使用%s或str()来显示存储在十进制中的完整值。
鉴于:
from decimal import Decimal
foo = Decimal("23380.06198573179271708683473")
print("{0:f}".format(foo))
print("%s" % foo)
print("%f" % foo)
Run Code Online (Sandbox Code Playgroud)
输出:
23380.06198573179271708683473
23380.06198573179271708683473
23380.061986
Run Code Online (Sandbox Code Playgroud)
(ed:更新以反映@Mark 的评论。)