Skip to content

Instantly share code, notes, and snippets.

@uluQulu
Last active November 4, 2018 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uluQulu/4450be0ef8662b72ab6c7f1694f7fb25 to your computer and use it in GitHub Desktop.
Save uluQulu/4450be0ef8662b72ab6c7f1694f7fb25 to your computer and use it in GitHub Desktop.
Truncate (shorten) a floating point value at given precision.
def truncate_float(number, precision, round=False):
""" Truncate (shorten) a floating point value at given precision """
# don't allow a negative precision [by mistake?]
precision = abs(precision)
if round:
# python 2.7+ supported method [recommended]
short_float = round(number, precision)
# python 2.6+ supported method
"""short_float = float("{0:.{1}f}".format(number, precision))
"""
else:
operate_on = 1 # returns the absolute number (e.g. 11.0 from 11.456)
for i in range(precision):
operate_on *= 10
short_float = float(int(number*operate_on)) / operate_on
return short_float
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment