simple string format question

Adrien adnothing at gmail.com
Mon Oct 15 08:58:09 EDT 2012


Le 15/10/2012 14:12, Neal Becker a écrit :
> Is there a way to specify to format I want a floating point written with no more
> than e.g., 2 digits after the decimal?  I tried {:.2f}, but then I get all
> floats written with 2 digits, even if they are 0:
>
> 2.35 << yes, that's what I want
> 2.00 << no, I want just 2 or 2.

Maybe you're looking for "{:.3g}"

print "{:.3g}".format(2)
# '2'

print "{:.3g}".format(2.00)
# '2'

print "{:.3g}".format(2.35)
# '2.35'

print "{:.3g}".format(2.356)  # this rounds up
# '2.36'

Cheers,

-- Adrien




More information about the Python-list mailing list