Last active
August 29, 2015 14:06
-
-
Save alaudet/8c950a129884885833fb to your computer and use it in GitHub Desktop.
Decimalize floats with the python decimal module
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
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