作为一个绝对的初学者,我如何在 python 3.2.5 中使用 %.2f 和变量?
As an absolute beginner how do I use %.2f with variables in python 3.2.5?
我刚开始使用 Python 来学习高中计算机科学,我正在使用 print
命令。我正在学习使用变量的 %.2f
舍入技术,但是,课程尚不清楚。我不确定将 %.2f
放在字符串中的什么位置,以及如何将 %
符号与变量放在一起。我的代码如下。也许有人可以指出我正确的方向?
Wage = 10.25 # sets wage as 10.25
Hours = 29 # sets hours as 29
Pay = Wage * Hours # uses hours and wage to determine pay
print("A student works for 29 hours at .25/hour. Their %.2f pay is", "$"+ %Pay)
您询问的代码位将浮点数减少到一定数量的十进制数字。用法是这样的:
num = 0.1234
print("%.2f" % num)
>>>> 0.12
%
表示变量,%f
表示是float。 .2
声明您需要两位数。外层 %
表示您要将内层 %
替换为的变量。
另一种舍入方式是使用 round
.
#The first number, 12345.54321 is what will be rounded. The second, 2, is how many decimals it will be rounded to.
round(12345.54321,2)
我刚开始使用 Python 来学习高中计算机科学,我正在使用 print
命令。我正在学习使用变量的 %.2f
舍入技术,但是,课程尚不清楚。我不确定将 %.2f
放在字符串中的什么位置,以及如何将 %
符号与变量放在一起。我的代码如下。也许有人可以指出我正确的方向?
Wage = 10.25 # sets wage as 10.25
Hours = 29 # sets hours as 29
Pay = Wage * Hours # uses hours and wage to determine pay
print("A student works for 29 hours at .25/hour. Their %.2f pay is", "$"+ %Pay)
您询问的代码位将浮点数减少到一定数量的十进制数字。用法是这样的:
num = 0.1234
print("%.2f" % num)
>>>> 0.12
%
表示变量,%f
表示是float。 .2
声明您需要两位数。外层 %
表示您要将内层 %
替换为的变量。
另一种舍入方式是使用 round
.
#The first number, 12345.54321 is what will be rounded. The second, 2, is how many decimals it will be rounded to.
round(12345.54321,2)