我试图根据用户输入计算一个数字。在显示它时,我想要它舍入到2位数。它也拒绝了!如此迷茫。有什么建议吗?
def calc(user_id):
numbers = {'A': 4, 'B': 3, 'C': 2, 'D': 1, 'F': 0}
user = User.objects.get(pk=user_id)
user_profile = UserProfile.objects.get(user=user)
outs = Out.objects.filter(user=user)
counter = 0
total_number = 0
for out in outs:
if out.data['type'] != 'panel':
continue
else:
print out.data
total_number += numbers[out.data['level']]
counter += 1
x = round(float(total_number/float(counter)), 2)
user_profile.average = x
user_profile.save()
答案 0 :(得分:1)
检查以下代码行:
total_number += numbers[out.data['level']]
如果您收到Keyerror,那么您的问题就出在该特定行。如果你发布缩进的代码,那将会更具可读性
def calc(user_id):
numbers = {'A': 4, 'B': 3, 'C': 2, 'D': 1, 'F': 0}
user = User.objects.get(pk=user_id)
user_profile = UserProfile.objects.get(user=user)
outs = Out.objects.filter(user=user)
counter = 0
total_number = 0
for out in outs:
if out.data['type'] != 'panel':
continue
else:
print out.data
total_number += numbers[out.data['level']]
counter += 1
x = round(float(total_number/float(counter)), 2)
user_profile.average = x
user_profile.save()
如果您需要精度,请使用固定和浮点运算。检查这个模块
此外,它可以确保您的round命令正常工作,但您的数字不能完全用二进制浮点表示。如果您需要打印可以使用的号码:
"%.1f" % n
答案 1 :(得分:0)
我不相信你需要使用round()。
字符串格式是要走的路。见这里:Formatted strings for rounding in python