I created a function for giving me percentages from two integers. I want two decimal places in the result.

def percent(num1, num2):
    num1 = float(num1)
    num2 = float(num2)
    percentage = '{0:.2f}'.format((num1 / num2 * 100))
    return percentage

It works, but I doubt it's very pythonic (since I have no idea what I'm doing)

>> print percent(1234, 5678)
  • \$\begingroup\$ Is there a better way to format to 2 decimal places? I would prefer to get a float as a result instead of a string. \$\endgroup\$ – Xodarap777 Nov 12 '14 at 0:22

In Python 3.0 or later, you do not need to explicitly convert your numbers to float. This is because the / operator always does floating point division (the // operator does "floor" division).

For older versions of Python (2.2 or later), you can use:

from __future__ import division

which changes the old meaning of / to the above. This makes the operation of / more predictable as the result no longer depends on the type of the inputs.

  • \$\begingroup\$ This has never appeared to be true to me. I'm using 2.7. Are you referring to 3? Removing the float conversion, I get 0.00 as my result. \$\endgroup\$ – Xodarap777 Nov 12 '14 at 0:17
  • \$\begingroup\$ I've updated my answer to better reflect reality. \$\endgroup\$ – Greg Hewgill Nov 12 '14 at 0:19
  • \$\begingroup\$ And I added the 2.7 tag. \$\endgroup\$ – Xodarap777 Nov 12 '14 at 0:22

You can also get rid of the temporary variable:

percentage = '{0:.2f}'.format((num1 / num2 * 100))
return percentage


return '{0:.2f}'.format((num1 / num2 * 100))

to return a float use:

def percentage(a, b):
    return round(a / b * 100, 2)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.