【问题标题】:How do you round all decimal places to 2?你如何将所有小数位四舍五入到2?
【发布时间】:2022-01-06 00:48:37
【问题描述】:

Python 新手和 Code 新手。我“知道”如何使用 round 函数,并且可以将它用于具有超过 2 个小数位的数字。我的问题是如何获得只有一位小数的数字来添加零以使其保留两位小数。比如美元金额?

这是我写的东西,欢迎任何离题或批评的建议。我已经知道我的数学有点“创造性”。我可以保证有一个更简单的方法,但我只是让它工作。也许如果有人可以向我解释我如何在这段代码中使用 f 字符串,那也很棒。

谢谢

print("Welcome to the tip calculator!")
total = input("What was the total bill? ")
tip = input("How much tip would you like to give? 10, 12, or 15? ")
split = input("How many people to split the bill? ")

total_float = float(total)
tip_float = float(tip)
tip_float /= 10.00**2.00
tip_float += 1.00
split_float = float(split)

each_pay = total_float * tip_float
each_pay /= 1.00
each_pay /=split_float

each_pay_str = str(round(each_pay, 2))
print("Each person should pay: $",each_pay_str )

【问题讨论】:

标签: python rounding f-string


【解决方案1】:

你可以使用f-string:

each_pay = 1.1
print(f"Each person should pay: ${each_pay:.2f}") # Each person should pay: $1.10

请注意,您甚至不需要 each_pay_str = str(round(each_pay, 2)) 行。通常最好保留一个数字(浮点数),仅在需要时进行转换。在这里,f-string 自动将其转换为字符串。

【讨论】:

    【解决方案2】:

    你可以这样做:

    x = '%.2f' % (f)
    

    或者为了让它更优雅,你可以这样做:

    f'{f:.2f}'
    

    【讨论】:

    • f'{f:%.2f}' 不起作用。它给出“ValueError:无效的格式说明符”。
    • 抱歉,这里不应该有百分比符号。我会编辑那个
    【解决方案3】:

    需要意识到的是round() 接受一个浮点数并给你一个浮点数。因此,round(1.234, 2) 将返回 1.23。但是,答案仍然是浮动的。您要问的是数字的字符串表示形式,即它在屏幕上的显示方式,而不是实际值。 (毕竟,1.1.0 实际上只是相同的值,0 对浮点数没有任何作用)

    你可以这样做:

    print(f'{1.234:.2f}')
    

    或者:

    s = f'{1.234:.2f}'
    print(s)
    

    这也适用于不需要那么多数字的数字:

    print(f'{1:.2f}')
    

    这样做的原因是 f-string 只是创建一个表示数值的字符串值。

    【讨论】:

      【解决方案4】:

      使用python的“格式化”函数添加N个小数位

      print(10.1) 10.1

      print(format(10.1,".2f")) 10.10(.2f 表示要添加的小数)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-12
        • 2013-08-14
        相关资源
        最近更新 更多