Created
June 24, 2010 20:53
-
-
Save lgastako/451959 to your computer and use it in GitHub Desktop.
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
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 |
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 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