Formatting numbers
Steve Holden
sholden at holdenweb.com
Tue May 1 22:15:23 EDT 2001
"Matthew Dixon Cowles" <matt at mondoinfo.com> wrote in ...
> On Tue, 1 May 2001 16:13:30 -0700, Daniel Klein <DanielK at jBASE.com>
> wrote:
>
> >Given an integer, 12345, how to format this to 123.45 ?
>
> Here's one way:
>
> >>> 12345/100.0
> 123.45
>
> You need the ".0" or at least the dot in order to force floating-point
> division.
>
But:
>>> 12340/100.0
123.40000000000001
>>> 12300/100.0
123.0
so this won't be useful in the general case. One way might be:
>>> def fmt(i):
... bits = divmod(i, 100)
... return "%d.%02d" % bits
...
>>> fmt(12345)
'123.45'
>>> fmt(12340)
'123.40'
>>> fmt(12300)
'123.00'
The locale module also contains number formatting routines IIRC.
regards
Steve
More information about the Python-list
mailing list