这里有很多关于如何将字符串转换为小数的主题,但是我该如何将小数转换回字符串?
比如说,如果我做了这个:
import decimal
dec = decimal.Decimal('10.0')
如何将dec
转换为字符串'10.0'
?
使用str()
内置函数,它:
返回一个包含对象可打印表示的字符串。
例如:
>>> import decimal
>>> dec = decimal.Decimal('10.0')
>>> str(dec)
'10.0'
str()
函数几乎可以用于任何类型的数据。 - Greg Hewgill0.0000000000000123123
这样的十进制字符串来说会失败,并且会打印出1.23123E-14
。@Matthew 是正确的(在下面的答案中),他使用了字符串格式化函数。 - Saikiran Yerram>>> from decimal import Decimal
>>> d = Decimal("0.0000000000000123123")
>>> s = '{0:f}'.format(d)
>>> print(s)
0.0000000000000123123
如果你只是将数字强制转换为字符串,对指数不起作用:
>>> str(d)
'1.23123E-14'
%f
字符串格式化似乎会先转换为浮点数(或只输出有限的小数位数),因此会损失精度。您应该使用%s
或str()
来显示存储在Decimal中的完整值。from decimal import Decimal
foo = Decimal("23380.06198573179271708683473")
print("{0:f}".format(foo))
print("%s" % foo)
print("%f" % foo)
输出:
23380.06198573179271708683473
23380.06198573179271708683473
23380.061986
(编辑:根据@Mark的评论进行了更新。)
%f
的格式化,但我没有看到任何答案建议使用这种方法。请注意,format(foo, 'f')
或 "{0:f}".format(foo)
不会将 foo
转换为浮点数或失去精度。 - Mark Dickinson>>> import decimal
>>> dec=decimal.Decimal('10.0')
一个字符串:
>>> str(dec)
'10.0'
浮动:
>>> float(dec)
10.0
一个整数:
>>> int(dec)
10
对象表示(就像在交互式解释器中一样):
>>> repr(dec)
"Decimal('10.0')"
有理数:
>>> import fractions
>>> fractions.Fraction(decimal.Decimal('0.50'))
Fraction(1, 2)
import decimal
dec = decimal.Decimal('10.0')
string_dec = str(dec)