>>> import decimal
>>> d = decimal.Decimal("9.0")
>>> d
Decimal('9.0')
>>> help(d.normalize)
Help on method normalize in module decimal:
normalize(self, context=None) method of decimal.Decimal instance
Normalize- strip trailing 0s, change anything equal to 0 to 0e0
>>> d.normalize()
Decimal('9')
>>> str(d)
'9.0'
>>> str(d.normalize())
'9'
Although it's possible that by "Decimal" you don't mean decimal.Decimal
. In that case, say "float" instead ;-)
EDIT: caution
By "trailing 0s", the docs mean all trailing zeroes, not necessarily just those "after the decimal point". For example,
>>> d = decimal.Decimal("100.000")
>>> d
Decimal('100.000')
>>> d.normalize()
Decimal('1E+2')
If that's not what you want, then I think you'll have to write your own function :-(
EDIT: trying a regexp
The normalize()
function here gets a lot closer to what I guess you want:
import re
trailing0 = re.compile(r"""(\. # decimal point
\d*?) # and as few digits as possible
0+$ # before at least 1 trailing 0
""", re.VERBOSE)
def replacer(m):
g = m.group(1)
if len(g) == 1:
assert g == "."
return ""
else:
return g
def normalize(x):
return trailing0.sub(replacer, str(x))
Then, e.g.,
from decimal import Decimal as D
for x in 1.0, 2, 10.010, D("1000.0000"), D("10.5"), D("9.0"):
print str(x), "->", normalize(x)
displays:
1.0 -> 1
2 -> 2
10.01 -> 10.01
1000.0000 -> 1000
10.5 -> 10.5
9.0 -> 9