printing float as formatted dollars

Larry Bates lbates at swamisoft.com
Tue May 4 14:29:39 EDT 2004


Here is a function I wrote and use.  Note: floats
have rounding "issues" when they get very large.

def fmt_wcommas(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
    #print "whole_part=",whole_part," fractional_part=",fractional_part
    #
    # Convert to string
    #
    temp="%i" % whole_part
    #
    # Convert the digits to a list
    #
    digits=list(temp)
    #print "digits=", digits
    #
    # 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)
    #print "padchars=",padchars
    if padchars != 3: digits=tuple(padchars*[' ']+digits)
    else:             digits=tuple(digits)
    #print "digits='%s'" % str(digits)
    #
    # Create the mask for formatting the string
    #
    sections=len(digits)/3
    mask=sections*",%s%s%s"
    outstring=mask % digits
    #
    # Drop off the leading comma and add currency and sign
    #
    outstring=sign+"$"+outstring[1:].lstrip()
    #print "outstring (int)=", outstring
    #
    # Add back the fractional part
    #
    outstring+=("%.2f" % fractional_part)[1:]
    #
    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_wcommas(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_wcommas(float(sign*invalue)+.01)


"Tim" <nospam-trice at comcast-nospam.net> wrote in message
news:aNadndnHDepsqQjd4p2dnA at adelphia.com...
> Is there a simple way to output float values as formatted dollar amounts?
> i.e. 127379.42  as  $127,379.42
>
> Thanks,
> Tim
>
>
>
>





More information about the Python-list mailing list