首页 > 解决方案 > 如何在 python 中将浮点数格式化为字符串?

问题描述

def main():
    M = float(input('Please enter sales for Monday: '))
    T = float(input('Please enter sales for Tuesday: '))
    W = float(input('Please enter sales for Wednesday: '))
    R = float(input('Please enter sales for Thursday: '))
    F = float(input('Please enter sales for Friday: '))
    sales = [M, T, W, R, F]

        total = 0 

    for value in sales:
        total += value

    print ('The total sales for the week are: $',total('.2f'))

main()

使用.2f格式我得到这个异常:

TypeError: 'float' object is not callable

如果我删除.2f脚本运行正常但格式不是我想要的,它显示为:

The total sales for the week are: $ 2500.0

我希望它有 2 个小数位,并且 $ 符号之间没有空格。

对 python 和学习基础知识仍然很陌生。非常感谢您的帮助。

标签: pythonpython-3.7

解决方案


这是使用 python 的 3 f-string 功能的解决方案

print (f'The total sales for the week are: {total:.2f}')

推荐阅读