Last active
November 4, 2018 17:18
-
-
Save uluQulu/4450be0ef8662b72ab6c7f1694f7fb25 to your computer and use it in GitHub Desktop.
Truncate (shorten) a floating point value at given precision.
This file contains hidden or 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_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