简体   繁体   English

不会将字符串格式的十进制数字转换为浮点数

[英]Wont convert decimal number in string format to float

I have a problem with my code and I just don't understand why its not working. 我的代码有问题,我只是不明白为什么它不起作用。 The code: 编码:

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)

The total_product when printed to console is: 当打印到控制台时,total_product为:

5.94
807.92
2000.40
0.00

What I don't understand is why its not converting each of those to floats and instead prints error to console: 我不明白的是为什么它不将每个转换成浮点型,而是将错误打印到控制台:

TypeError: cannot concatenate 'str' and 'float' objects TypeError:无法连接'str''float'对象

I would love it if someone could tell me how to fix it or/and why its doing it. 如果有人可以告诉我如何修复或/以及为什么要这样做,我将非常乐意。

Your code actually is successfully converting each of the total_product s to a float. 您的代码实际上已成功地将每个total_product转换为float。 The error is in the last line of your snippet where you try to concatenate your string output with the value of your total variable (which is still a float). 错误出现在代码段的最后一行,您尝试将字符串输出与total变量的值(仍然是浮点数)连接在一起。 You should use either string formatting (recommended solution): 您应该使用任一字符串格式(推荐的解决方案):

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

or just cast your float to a string: 或只是将您的浮动对象转换为字符串:

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

Convert the total variable which is type float to a string 将类型为floattotal变量转换为string

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

Here is an example: 这是一个例子:

total = 13.54
str(total)
>> '13.54'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM