patternpythonMinor
Function to return percentages in Python
Viewed 0 times
returnfunctionpythonpercentages
Problem
I created a function for giving me percentages from two integers. I want two decimal places in the result.
It works, but I doubt it's very pythonic (since I have no idea what I'm doing)
def percent(num1, num2):
num1 = float(num1)
num2 = float(num2)
percentage = '{0:.2f}'.format((num1 / num2 * 100))
return percentageIt works, but I doubt it's very pythonic (since I have no idea what I'm doing)
>> print percent(1234, 5678)
21.73Solution
In Python 3.0 or later, you do not need to explicitly convert your numbers to
For older versions of Python (2.2 or later), you can use:
which changes the old meaning of
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 divisionwhich 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.Code Snippets
from __future__ import divisionContext
StackExchange Code Review Q#69542, answer score: 6
Revisions (0)
No revisions yet.