Currency format for floats?

Joseph Santaniello joseph at src.no
Fri Jun 2 12:29:52 EDT 2000


Nice!

I gave up on a locale way, but this is just what I needed. Thanks
everybody!

Joe

On Thu, 1 Jun 2000, Andrew Dalke wrote:

> 
> Joseph Santaniello wrote:
> >Ah, yes. But I'm still missing my commas [for 23,342.40]... A nice
> > clean way to do that?
> 
> I think the following is only somewhat tricky, but perhaps the
> cleanest.  (Okay, there's also supposed to be a way to do this with
> locale, but I don't know how.)
> 
> def dollar(f):
>   if f < 0:     # pull the sign out now so I know where to stop
>     sign = "-"  # when going bacwards
>     f = -f
>   else:
>     sign = ""
> 
>   s = "%.2f" % f
>   # -6 is the thousand's place  --  987654.21
>   # -3 goes back 1000 at a time
>   # stop at 0 instead of -1 so "999.99" doesn't lead with a ",".
>   for i in range(len(s)-6, 0, -3):  # -6 is the first thousands place
>     s = s[:i] + "," + s[i:]         # Go back 1000 at a time
>   return sign + s
> 
> >>> for i in (0, .9, 1, 10, 99.99, 100.00, 100.0, 999.99, 1000.,
>   1000.00, 1000000000L, -0.01, -0.9, -1, -99.9, -100, -999.99, -1000.00,
>   -123456789):
> ...  print i, dollar(i)
> ...
> 0 0.00
> 0.9 0.90
> 1 1.00
> 10 10.00
> 99.99 99.99
> 100.0 100.00
> 100.0 100.00
> 999.99 999.99
> 1000.0 1,000.00
> 1000.0 1,000.00
> 1000000000L 1,000,000,000.00
> -0.01 -0.01
> -0.9 -0.90
> -1 -1.00
> -99.9 -99.90
> -100 -100.00
> -999.99 -999.99
> -1000.0 -1,000.00
> -123456789 -123,456,789.00
> 
>                     Andrew
>                     dalke at acm.org
> 
> 
> 
> 




More information about the Python-list mailing list