Python 3 - 将字符串转换为数字

Python 3 - convert string into a number

我正在使用 python 和 django,但我遇到了这个问题:我有不同的变量来存储对象的价格,所有变量的格式都类似于 350.32182.40, 等等...

我的问题是这些数字是字符串,但在我的函数中我必须对它们求和才能达到总数,而 python 不允许我这样做,因为它不能对字符串求和。我试过 int()float()format()Decimal(),但它们总是给我一个只有一位小数的值或其他不正确的值。我需要 2 个十进制数,我需要将它们全部相加的可能性。我该怎么做?

PS: 对于任何英语错误,我很抱歉,我是意大利人。

我正在使用 Python 3.4.0,这对我有用:

>>>a = '350.32'
>>>float(a)
350.32

要将其四舍五入到小数点后两位,请执行以下操作:

>>>b = '53.4564564'
>>>round(float(b), 2)
53.46
import re

eggs = "12.4, 15.5, 77.2"

print(sum(map(float, re.split("\s*,\s*", eggs))))

小数似乎适合我。

如果这些是价格,请不要将它们存储为浮点数...floats will not give you exact numbers for decimal amounts like prices

>>> from decimal import Decimal
>>> a = Decimal('1.23')
>>> b = Decimal('4.56')
>>> c = a + b
>>> c
Decimal('5.79')

这给出了小数点后五位的完美十进制值

import random
from decimal import Decimal  

def myrandom():
    for i in range(10):
        Rand = Decimal(random.random()* (0.909 - 0.101) + 0.101)
        Rand = '{0:0.5f}'.format(Rand)
        print (Rand)

myrandom()