-1

I am trying to get this to calculate a number based on user input. While displaying it I want it to round to 2 digits. It refuses too! So confused. Any advice?

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()
2
  • What exactly is getting displayed? This could be a case of floating-point math inaccuracy. Commented Aug 9, 2014 at 2:16
  • Please indent your code and add an example of your output Commented Aug 9, 2014 at 2:24

2 Answers 2

1

Check this line of code:

total_number += numbers[out.data['level']]

if you are receiving a Keyerror, your problem is in that particular line. If you post your code indented, is going to be much more readable

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()

UPDATE

If you need precision, work with fixed and floating point arithmetic. check this module

http://pymotw.com/2/decimal/

Also, its posible that your round command works correctly but your number cannot be represented exactly in binary floating point. If you need to print the number you can use:

"%.1f" % n
Sign up to request clarification or add additional context in comments.

3 Comments

There is no error presented, it generates but it simply doesn't round the number. Thank you for the indents! I will make sure to do that next time.
You are welcome, please edit your post with more details like examples of your output or little pieces of data input
Also you dont need to cast to float twice in float(total_number/float(counter)). Just put round(total_number/float(counter), 2). Maybe that's causing your problem
0

I don't believe you need to use round().

The string formatting is the way to go. See here: Formatted strings for rounding in python

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.