Last active
December 1, 2015 21:54
-
-
Save eligundry/5be3bcefae26ef101650 to your computer and use it in GitHub Desktop.
Python Correctly Trim Decimals
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 | |
def trim_decimal(value): | |
if isinstance(value, (decimal.Decimal, float)): | |
# I think format was something Django specific, because I don't know where it came from or what it does. | |
value = format(value, 'f') | |
s = str(value) | |
return s.rstrip('0').rstrip('.') if '.' in s else s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
format
is a Python built-in @eligundry. And you just gave me my first example of using it. It calls the__format__
magic method, which has it's own little special formatting DSL built-in and what not. Just supports advanced string casting for an object into different representations, I do believe (e.g.,i
for int, andf
for float).