Skip to content

Instantly share code, notes, and snippets.

@lgastako
Created June 24, 2010 20:53
Show Gist options
  • Save lgastako/451959 to your computer and use it in GitHub Desktop.
Save lgastako/451959 to your computer and use it in GitHub Desktop.
from __future__ import unicode_literals
def decimal_to_unicode(d, strip=True):
"""Converts a decimal to a unicode string stripping any redundant
trailing zeros to the right of the decimal place if strip is True.
>>> from decimal import Decimal
>>> decimal_to_unicode(Decimal("1.234000"))
u'1.234'
>>> decimal_to_unicode(Decimal("1.0"))
u'1.0'
>>> decimal_to_unicode(Decimal("1.2345678"))
u'1.2345678'
"""
u = unicode(d)
if strip and "." in u:
u = u.rstrip("0")
if u[-1] == ".":
u = u + "0"
return u
import re
STRIP_RE = re.compile(r"\d+\.\d+(0*)")
def re_decimal_to_unicode(d, strip=True):
"""Converts a decimal to a unicode string stripping any redundant
trailing zeros to the right of the decimal place if strip is True.
>>> from decimal import Decimal
>>> decimal_to_unicode(Decimal("1.234000"))
u'1.234'
>>> decimal_to_unicode(Decimal("1.0"))
u'1.0'
>>> decimal_to_unicode(Decimal("1.2345678"))
u'1.2345678'
"""
u = unicode(d)
if strip:
u = STRIP_RE.sub("", u)
return u
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment