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


Groups > comp.lang.python > #32122

Re: simple string format question

From Neil Cerutti <neilc@norwich.edu>
Newsgroups comp.lang.python
Subject Re: simple string format question
Date 2012-10-25 12:49 +0000
Organization Norwich University
Message-ID <aesqqgFlq7dU1@mid.individual.net> (permalink)
References <k5guje$ui$1@ger.gmane.org> <mailman.2200.1350305892.27098.python-list@python.org> <m27gqfkya5.fsf@cochabamba.vanoostrum.org>

Show all headers | View raw


On 2012-10-25, Piet van Oostrum <piet@vanoostrum.org> wrote:
> Adrien <adnothing@gmail.com> writes:
>
>> print "{:.3g}".format(2.356)  # this rounds up
>
> But:
>
>>>> print "{:.3g}".format(12.356) 
> 12.4
>>>> print "{:.3g}".format(123.356) 
> 123


  The precision is a decimal number indicating how many digits
  should be displayed after the decimal point for a floating
  point value formatted with 'f' and 'F', or before and after the
  decimal point for a floating point value formatted with 'g' or
  'G'. For non-number types the field indicates the maximum field
  size - in other words, how many characters will be used from
  the field content. The precision is not allowed for integer
  values.

So g will print a specific number of significant digits, so it
won't do what Adrien wants.

And f will print a fixed number of digits after the decimal
point, so it won't do want Adrien wants.

Adrien, you will need to do some post-processing on fixed point
output to remove trailing zeroes.

>>> print("{:.2f}".format(2.1).rstrip('0'))
2.1
>>> print("{:.2f}".format(2.127).rstrip('0'))
2.13

-- 
Neil Cerutti

Back to comp.lang.python | Previous | NextPrevious 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