Created
May 26, 2018 22:25
-
-
Save samclane/0fa182b428ddfb631bfc0d173a727ea0 to your computer and use it in GitHub Desktop.
Decorator that truncates all decimal arguments of wrapped function to n digits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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