Skip to content

Instantly share code, notes, and snippets.

@eligundry
Last active December 1, 2015 21:54
Show Gist options
  • Save eligundry/5be3bcefae26ef101650 to your computer and use it in GitHub Desktop.
Save eligundry/5be3bcefae26ef101650 to your computer and use it in GitHub Desktop.
Python Correctly Trim Decimals
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
@nnewman
Copy link

nnewman commented Dec 1, 2015

Missing an extra ')' on line 4

@hjc
Copy link

hjc commented Dec 1, 2015

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, and f for float).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment