不要将字符串格式的十进制数转换为float

时间:2016-02-17 15:56:59

标签: python python-2.7

我的代码有问题,我只是不明白为什么它不起作用。代码:

total = 0
with open("receipt.txt", "r") as receipt:
    for line in receipt:
        the_line = line.split(",")
        total_product = the_line[4]
        total_product = total_product.translate(None, '\n')
        print total_product
        total += float(total_product)

with open("receipt.txt", "a") as receipt:
    receipt.write("Total of Items:            " + total)

打印到控制台时的total_product是:

5.94
807.92
2000.40
0.00

我不明白为什么它不会将每个转换为浮点数而是将错误输出到控制台:

  

TypeError:无法连接'str''float'个对象

如果有人可以告诉我如何修复它或/以及为什么要这样做,我会很高兴。

2 个答案:

答案 0 :(得分:4)

您的代码实际上已成功将每个total_product转换为浮点数。错误位于代码段的最后一行,您尝试将字符串输出与total变量(仍为浮点数)的值连接起来。您应该使用字符串格式(推荐的解决方案):

with open("receipt.txt", "a") as receipt:
    receipt.write("Total of Items:            {:.2f}".format(total))

或者只是将你的浮动转换为字符串:

with open("receipt.txt", "a") as receipt:
    receipt.write("Total of Items:            " + str(total))

答案 1 :(得分:2)

将类型为total的{​​{1}}变量转换为float

string

以下是一个例子:

receipt.write("Total of Items:            " + str(total))