Skip to content

Instantly share code, notes, and snippets.

@samclane
Created May 26, 2018 22:25
Show Gist options
  • Save samclane/0fa182b428ddfb631bfc0d173a727ea0 to your computer and use it in GitHub Desktop.
Save samclane/0fa182b428ddfb631bfc0d173a727ea0 to your computer and use it in GitHub Desktop.
Decorator that truncates all decimal arguments of wrapped function to n digits
def truncate(f, n):
'''Truncates/pads a float f to n decimal places without rounding'''
s = '{}'.format(f)
if 'e' in s or 'E' in s:
return '{0:.{1}f}'.format(f, n)
i, p, d = s.partition('.')
return float('.'.join([i, (d+'0'*n)[:n]]))
def truncate_args(digits):
def decorator(func):
def wrapper(*args):
args = (truncate(x, digits) for x in args)
return func(*args)
return wrapper
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment