String Formatting Operations for decimals.

Maxim Lacrima lacrima.maxim at gmail.com
Thu Apr 1 05:24:07 EDT 2010


Hello, Chris!

Thanks for your really quick reply! It works!


On 1 April 2010 12:14, Chris Rebert <clp2 at rebertia.com> wrote:

> On Thu, Apr 1, 2010 at 2:08 AM, Lacrima <lacrima.maxim at gmail.com> wrote:
> > Hello!
> >
> > I need to format a decimal (floating point) number in the following
> > way:
> > 10 results in '10'
> > 10.5 results in '10.5'
> > 10.50 results in '10.5'
> > 10.5678 results in 10.57
> >
> > How can I achieve this using standard Python string formatting
> > operations?
> > Something like '%.2f' works almost as expected:
> >>>> '%.2f' % 10.5
> > '10.50'
> >>>> '%.2f' % 10.5678
> > '10.57'
> >>>> '%.2f' % 10
> > '10.00'
> > But I always need trailing zeros to be excluded, i.e. 10.5 should
> > result in '10.5' (not '10.50'), and 10 should result in '10' (not
> > '10.00').
> > So how can I do this?
>
> ('%.2f' % 10).rstrip('0').rstrip('.')
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>



-- 
with regards,
Maxim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100401/0d2d2b58/attachment-0001.html>


More information about the Python-list mailing list