如何在python中将浮点数格式化为字符串? [英] How can I format a float as a string in python?

查看:139
本文介绍了如何在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 格式时,我收到此异常:

With the .2f format I am getting this exception:

TypeError: 'float' object is not callable

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

If I remove the .2f the script runs properly but the formatting is not how I would like it, it displays as:

The total sales for the week are: $ 2500.0

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

I would prefer to have it so that there are 2 decimal places and no space between the $ sign.

对 Python 还是个新手,正在学习基础知识.非常感谢您的帮助.

Still new to python and learning the basics. Your help is greatly appreciated.

推荐答案

replace

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

为了

print ('The total sales for the week are: $',"{0:.2f}".format(total))

这篇关于如何在python中将浮点数格式化为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆