String formatting (%)

Larry Bates lbates at swamisoft.com
Wed Apr 28 11:01:53 EDT 2004


Pascal,

Here is a function that I had that does what you want.
Warning-If the floats get very large it breaks down.

Larry Bates
Syscon, Inc.

def fmt_wspaces(amount):
    #
    # This function will take the number passed to it and format it with
    # spaces as thousands separators.
    #
    # If I got zero return zero (0.00)
    #
    if not amount: return '0.00'
    #
    # Handle negative numbers
    #
    if amount < 0: sign="-"
    else:          sign=""
    #
    # Split into fractional and whole parts
    #
    whole_part=abs(long(amount))
    fractional_part=abs(amount)-whole_part
    #
    # Convert to string
    #
    temp="%i" % whole_part
    #
    # Convert the digits to a list
    #
    digits=list(temp)
    #
    # Calculate the pad length to fill out a complete thousand and add
    # the pad characters (space(s)) to the beginning of the string.
    #
    padchars=3-(len(digits)%3)
    if padchars != 3: digits=tuple(padchars*[' ']+digits)
    else:             digits=tuple(digits)
    #
    # Create the mask for formatting the string
    #
    sections=len(digits)/3
    mask=sections*" %s%s%s"
    if _debug > 2: logf.writelines("D","mask=%s" % mask)
    outstring=mask % digits
    #
    # Drop off the leading space and add back the sign
    #
    outstring=sign+outstring[1:].lstrip()
    #
    # Add back the fractional part
    #
    outstring+="%.2f" % fractional_part
    #
    return outstring

if __name__=="__main__":

    print "----------testing negative floats------------------------------"
    sign=-1
    invalue=0L
    for j in range(2):
        for i in range(1,10):
            invalue=invalue*10+i
            print fmt_wspaces(float(sign*invalue)-.01)

    print "----------testing positive floats------------------------------"
    sign=1
    invalue=0L
    for j in range(2):
        for i in range(1,10):
            invalue=invalue*10+i
            print fmt_wspaces(float(sign*invalue)+.01)



"Pascal" <pascal.parent at free.fr> wrote in message
news:e567c03a.0404280035.79d0d973 at posting.google.com...
> Hello,
> I've a float number 123456789.01 and, I'de like to format it like this
> "123 456 789.01".
> Is this possible with % character?





More information about the Python-list mailing list