Skip to content

Instantly share code, notes, and snippets.

@alaudet
Last active August 29, 2015 14:06
Show Gist options
  • Save alaudet/8c950a129884885833fb to your computer and use it in GitHub Desktop.
Save alaudet/8c950a129884885833fb to your computer and use it in GitHub Desktop.
Decimalize floats with the python decimal module
import decimal
value1 = 29.458699990
value2 = 0.458699990
decimal_places = 2
def decimalize(value, decimal_places):
"""Round a value to a specified decimal place."""
left_of_decimal, the_decimal, right_of_decimal = str(value).partition(".")
if left_of_decimal == str(0):
decimal_places -= 1
decimal.getcontext().prec = len(left_of_decimal) + decimal_places
return decimal.Decimal(value) * 1
# decimalize(value1, decimal_places)
# decimalize(value2, decimal_places)
# Output
# ------
# 29.46
# 0.46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment