Floating Number format problem

Peter Otten __peter__ at web.de
Tue Jun 12 12:42:48 CEST 2007


Marc Christiansen wrote:

> Gabriel Genellina <gagsl-py2 at yahoo.com.ar> wrote:
>> En Tue, 12 Jun 2007 05:46:25 -0300, <kelvin.you at gmail.com> escribió:
>> 
>>> On 6 12 ,   3 16 , ici <iltch... at gmail.com> wrote:
>>>> On Jun 12, 10:10 am,                 <kelvin.... at gmail.com> wrote:
>>>>
>>>> > How could I format the float number like this: (keep 2 digit
>>>> > precision)
>>>> > 1.002 => 1
>>>> > 1.12  => 1.12
>>>> >>> print "%.02f" % (2324.012)
>>>> 2324.01
> Or:
> 
> def my_other_formatter_ommitting_trailing_zeroes(value):
>     result = '%.2f' % value
>     return result.rstrip('0.')

Make that result.rstrip("0").rstrip("."), or it may fail:

>>> ("%.2f" % 100.0).rstrip(".0") 
'1' # wrong
>>> ("%.2f" % 100.0).rstrip("0").rstrip(".")
'100'

Peter



More information about the Python-list mailing list