# Floating Number format problem

John Machin sjmachin at lexicon.net
Tue Jun 12 12:43:22 CEST 2007

```On Jun 12, 8:04 pm, Marc Christiansen <use... at solar-empire.de> wrote:
> Gabriel Genellina <gagsl-... at yahoo.com.ar> wrote:
> > En Tue, 12 Jun 2007 05:46:25 -0300, <kelvin.... 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
>
> >> But in these case:
>
> >>>>> print '%.02f'%1.002
> >> 1.00
> >>>>> print '%.02f'%1.00
> >> 1.00
>
> >> I just expect it to output "1" , but these way will output 1.00
>
> > def my_formatter_ommitting_trailing_zeroes(value):
> >   result = '%.2f' % value
> >   if result[-3:]=='.00': result = result[:-3]
> >   return result
>
> > for f in [1.0, 1.002, 1.12, 1.567, 2324.012]:
> >   print "%g -> %s" % (f, my_formatter_ommitting_trailing_zeroes(f))
>
> Or:
>
> def my_other_formatter_ommitting_trailing_zeroes(value):
>     result = '%.2f' % value
>     return result.rstrip('0.')
>
> my_other_formatter_ommitting_trailing_zeroes(1.102) == "1.1"

Marc, thanks for coming, but:

>>> my_other_formatter_ommitting_trailing_zeroes(100.00)
'1'
>>>

What does the OP want to happen with 1.2? I suspect he wants '1.2',
not '1.20'

Looks like a variation of Marc's idea will do the business:
>>> values = [100.0, 1.0, 1.2, 1.002, 1.12, 1.567, 2324.012]
>>> [('%.02f' % x).rstrip('0').rstrip('.') for x in values]
['100', '1', '1.2', '1', '1.12', '1.57', '2324.01']

Howzat?

```