|
# (c) PSP UK Group Ltd. <[email protected]> |
|
# |
|
# For the full copyright and license information, |
|
# please view the LICENSE file that was distributed with this source code. |
|
|
|
import math |
|
|
|
from jinja2.exceptions import FilterArgumentError |
|
|
|
class FilterModule(object): |
|
""" Jinja2 filter for calculating percentages of a value. """ |
|
|
|
def percentage(self, value, percentage, precision=0, method='common', as_int=True, default=0): |
|
""" Calculate a percentage of a value, see Jinja2 round filter. """ |
|
if not method in ('common', 'ceil', 'floor'): |
|
raise FilterArgumentError('method must be common, ceil or floor') |
|
if percentage < 1: |
|
percentage = (float(percentage) * 100.00) |
|
try: |
|
result = ((float(value) / 100.0) * float(percentage)) |
|
except (TypeError, ValueError): |
|
return default |
|
if method == 'common': |
|
result = round(result, precision) |
|
else: |
|
func = getattr(math, method) |
|
result = func(result * (10 ** precision)) / (10 ** precision) |
|
if as_int: |
|
try: |
|
result = int(result) |
|
except (TypeError, ValueError): |
|
# this quirk is necessary so that "42.23"|int gives 42. |
|
try: |
|
result = int(float(result)) |
|
except (TypeError, ValueError): |
|
return default |
|
return result |
|
|
|
def filters(self): |
|
""" Export filters from this class to Jinja2/Ansible. """ |
|
return { |
|
'percentage': self.percentage, |
|
} |