"""Add commas to a number."""
## Created: Thu Jan 20 02:37:09 GMT 2005
## Author: Michael Olivier, Shannon -jj Behrens
## Email: jjinux@users.sourceforge.net
##
## Copyright (c) Michael Olivier, Shannon -jj Behrens. All rights reserved.
from aquarium.util.AquariumClass import AquariumClass
class ThousandsCommas(AquariumClass):
def __call__(self, n):
"""Return n after putting commas at the thousands marks.
n
This is the number to output.
It's safe to accidentally call this method twice on the same number.
Note that this widget is only appropriate for English. For instance,
in Germany, they reverse the meaning of commas and periods when writing
a decimal number.
"""
n = str(n)
if n.find(",") != -1:
return n
if n.find(".") != -1:
(whole, fractional) = n.split(".")
whole = self._addCommas(whole, False)
fractional = self._addCommas(fractional, True)
return "%s.%s" % (whole, fractional)
return self._addCommas(n, False)
def _addCommas(self, s, forward):
"""Add commas to s and return it.
forward:
Do we start at the left and work to the right?
"""
if forward:
i = 3
while i < len(s):
s = "%s,%s" % (s[:i], s[i:])
i += 4
else:
for i in range(len(s) - 3, 0, -3):
s = "%s,%s" % (s[:i], s[i:])
return s
# Do some testing.
if __name__ == "__main__":
from cStringIO import StringIO
buf = StringIO()
commas = ThousandsCommas(None)
for exp in range(10):
i = 10 ** exp
print >> buf, commas(i)
for exp in range(20):
i = 10 ** exp
print >> buf, commas("%s.%s" % (i, i))
print >> buf, commas(commas(5000.0001))
assert buf.getvalue() == """\
1
10
100
1,000
10,000
100,000
1,000,000
10,000,000
100,000,000
1,000,000,000
1.1
10.10
100.100
1,000.100,0
10,000.100,00
100,000.100,000
1,000,000.100,000,0
10,000,000.100,000,00
100,000,000.100,000,000
1,000,000,000.100,000,000,0
10,000,000,000.100,000,000,00
100,000,000,000.100,000,000,000
1,000,000,000,000.100,000,000,000,0
10,000,000,000,000.100,000,000,000,00
100,000,000,000,000.100,000,000,000,000
1,000,000,000,000,000.100,000,000,000,000,0
10,000,000,000,000,000.100,000,000,000,000,00
100,000,000,000,000,000.100,000,000,000,000,000
1,000,000,000,000,000,000.100,000,000,000,000,000,0
10,000,000,000,000,000,000.100,000,000,000,000,000,00
5,000.000,1
"""
buf.close()
|