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

时间:2012-06-10 18:55:40

标签: python python-2.7

以下类似帖子不回答我的问题。 Convert a string to integer with decimal in 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?

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

6 个答案:

答案 0 :(得分:3)

如果您希望保留decimal个数字,最安全的是转换所有内容:

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

>>> d - decimal.Decimal('1')
Decimal('22.456')
>>> d - decimal.Decimal('1.0')
Decimal('22.456')

在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'

答案 1 :(得分:1)

计算需要Decimal吗? Decimal fixed point and floating point arithmetic doc概述了他们之间的差异。如果没有,你可以做到

 d = float('23.456')
 d
 23.456

 d - 1
 22.456

奇怪的是Decimal,我以交互方式得到了这个

d = decimal.Decimal('23.456')

d
Decimal('23.456')
d - 1
Decimal('22.456')

但是当我打印它时,我得到了值

print d
23.456
print d-1
22.456

答案 2 :(得分:0)

使用bultin浮动函数:

>>> d = float('23.456')
>>> d
23.456
>>> d - 1
22.456

请参阅此处的文档:http://docs.python.org/library/functions.html#float

答案 3 :(得分:0)

我的Python似乎采用了不同的方式:

>>> s = '23.456'
>>> d = decimal.Decimal(s)
>>> d
Decimal('23.456')
>>> d-1
Decimal('22.456')

您使用的是什么版本/操作系统?

答案 4 :(得分:0)

你是专门尝试使用Decimal任意精度库还是只是在努力将字符串转换为Python float?

如果您正在尝试使用十进制:

>>> import decimal
>>> s1='23.456'
>>> s2='1.0'
>>> decimal.Decimal(s1) - decimal.Decimal(s2)
Decimal('22.456')
>>> s1='23.456'
>>> s2='1'
>>> decimal.Decimal(s1) - decimal.Decimal(s2)
Decimal('22.456')

或者,我认为更有可能的是,您尝试将字符串转换为Python浮点值:

>>> s1='23.456'
>>> s2='1'
>>> float(s1)-float(s2)
22.456
>>> float(s1)-1
22.456
>>> float(s1)-1.0
22.456

答案 5 :(得分:0)

如果使用float,当数字太大 - x = 29345678.91例如时 - 您会得到您可能不期望的结果。在这种情况下,float(x)变为 2.934567891E7 ,这似乎是不受欢迎的,尤其是在处理财务数字时。

相关问题