insert thousands separators
gyro
gyromagnetic at excite.com
Mon Jun 16 16:36:30 EDT 2003
Nick Vargish wrote:
> Gerhard Häring <gh at ghaering.de> writes:
>
>
>>So if you only want to print the fractional value, str() will do
>>fine. But str() won't make floats capable of representing arbitrary
>>numbers, either ;-)
>
>
> If I really cared about floats, I could str(fval).split('.') -- after
> checking for floatness, of course. But since I don't care about
> floats, I'm gonna let it ride for now -- until it bites me in some
> other context. :^)
>
> Nick
>
Hi,
How about the ugliness below for floating point numbers?
-g
===
def include_separator(val,thous_sep=',',dec_sep='.'):
"""Format a floating point number so that it has thousands
separators.
"""
import re
snum = str(val)
# regular expression for a general floating point number
num_regex = re.compile('''
(?P<msign>[-+])? # perhaps a leading
sign
((?P<mnum>[0-9]+)(?P<mfrc>\%s?[0-9]*)| # a number, a
separator, and a decimal part
(?P<mdec>\%s[0-9]+)) # or just a separator
and decimal part
(?P<mexp>[eE][-+]?[0-9]+)? # and perhaps an
exponent
''' % (dec_sep,dec_sep), re.VERBOSE)
msrch = num_regex.search(snum)
# find out which pieces of the general floating point number
# were found in the target
if msrch:
ms = msrch.group
msign = ms('msign') or ''
mnum = ms('mnum') or ''
mexp = ms('mexp') or ''
mfrc = ms('mfrc') or ''
mdec = ms('mdec') or ''
# put thousands separator in place in the whole number piece
if mnum:
if int(mnum) == 0: mnum = '0'
cc = []
rnum = list(mnum)
rnum.reverse()
i = 1
for dig in rnum:
cc.append(dig)
if i % 3 == 0 and i != len(rnum): cc.append(thous_sep)
i += 1
cc.reverse()
mnum = ''.join(cc)
# reassemble the pieces
fnum = msign + (mnum + mfrc or mdec) + mexp
return fnum
if __name__ == "__main__":
print include_separator('-12345.234')
print include_separator('-000000.00234')
print include_separator('-0.00234')
print include_separator(12345)
print include_separator('-12345,234e4','.',',')
print include_separator('1.234')
print include_separator('-123.234')
print include_separator('-123456,234','.',',')
More information about the Python-list
mailing list