如何在 Python 中将字符串转换为十进制数以进行算术运算?

ide*_*ikz 5 python python-2.7

类似的帖子(例如以下内容)没有回答我的问题。 在Python中将字符串转换为带小数的整数

考虑以下 Python 代码。

>>> import decimal
>>> s = '23.456'
>>> d = decimal.Decimal(s)
>>> d
Decimal('23.456')           # How do I represent this as simply 23.456?
>>> d - 1
22                          # How do I obtain the output to be 22.456?
Run Code Online (Sandbox Code Playgroud)

如何将字符串转换为十进制数,以便能够对其执行算术函数并获得具有正确精度的输出?

And*_*ffe 4

如果你想保留decimal数字,最安全的方法是转换所有内容:

>>> s = '23.456'
>>> d = decimal.Decimal(s)

>>> d - decimal.Decimal('1')
Decimal('22.456')
>>> d - decimal.Decimal('1.0')
Decimal('22.456')
Run Code Online (Sandbox Code Playgroud)

在 Python 2.7 中,有整数的隐式转换,但没有浮点数。

>>> d - 1
Decimal('22.456')
>>> d - 1.0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'Decimal' and 'float'
Run Code Online (Sandbox Code Playgroud)