Pretty-Print Large Numbers Atom Feed 0

In Brief Converts a float to a string with appropriately-placed commas.... more
# 's
 1# Copyright 2007 Regents of the University of California
2# Written by David Isaacson at the University of California, Davis
3# BSD License
4
5def PrintLargeNumber(n,width=2,delim=',',decimal='.'):
6 """
7 Converts a float to a string with appropriately placed commas.
8
9 Floats will be shown with 'width' digits right of the decimal.
10 'delim' specifies the thousands delimiter.
11 'decimal' specifies the decimal character.
12 """
13 if width >= 0: s = "%.*f" %(width,n)
14 else: s = str(n)
15 dec = s.find(decimal)
16 if dec == -1: dec = len(s)
17 threes = int((dec-1)/3) #we don't need a comma at the start
18 for i in xrange(threes):
19 loc = dec-3*(i+1)
20 s = s[:loc] + delim + s[loc:]
21 return s

Converts a float to a string with appropriately-placed commas.

Shows a selectable number of digits right of the decimal. Thousands delimiter and decimal characters are customizable.