Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #31295

Re: simple string format question

Date 2012-10-15 14:58 +0200
From Adrien <adnothing@gmail.com>
Subject Re: simple string format question
References <k5guje$ui$1@ger.gmane.org>
Newsgroups comp.lang.python
Message-ID <mailman.2200.1350305892.27098.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: simple string format question Adrien <adnothing@gmail.com> - 2012-10-15 14:58 +0200
  Re: simple string format question Piet van Oostrum <piet@vanoostrum.org> - 2012-10-24 23:48 -0400
    Re: simple string format question Neil Cerutti <neilc@norwich.edu> - 2012-10-25 12:49 +0000

csiph-web