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


Groups > comp.lang.python > #40605

Re: Controlling number of zeros of exponent in scientific notation

From Terry Reedy <tjreedy@udel.edu>
Subject Re: Controlling number of zeros of exponent in scientific notation
Date 2013-03-06 00:45 -0500
References <c2184b42-41be-4930-9501-361296df7679@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.2924.1362548730.2939.python-list@python.org> (permalink)

Show all headers | View raw


On 3/5/2013 3:09 PM, faraz@squashclub.org wrote:
> Instead of:
> 1.8e-04
> I need:
> 1.8e-004
>
> So two zeros before the 4, instead of the default 1.

The standard e and g float formats do not give you that kind of control 
over the exponent. You have to write code that forms the string you 
want. You can put that in a simple function or make a class with a 
__format__ method to tie into the new format() and str.format system.

 >>> class myfloat(float):
	def __format__(self, spec): return '3.14'
	
 >>> x = myfloat(1.4)
 >>> x
1.4
 >>> format(x, '')
'3.14'
 >>> '{}'.format(x)
'3.14'

You could write __format__ to use standard format specs and then adjust:

def __format__(self, spec):
   s = float.__format__(self, spec)
   <adjust s>
   return s

or generate the pieces of the string yourself, possibly using a custom 
spec, as opposed to the standard spec. Notice this example from the manual:
'''
Using type-specific formatting:

 >>> import datetime
 >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
 >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'
'''
This works because datetime.datetime and a .__format__ that interprets a 
highly customized format spec. You could customize myfloat's spec to add 
a value for the exponent width. Your example above might be '8.1.3e' 
instead of the standard '7.1e'

Standard, real:
 >>> format(1.8e-4, '7.1e')
'1.8e-04'

Custom, hypothetical:
 >>> format(myfloat(1.8e-4), '8.1.3e')
'1.8e-004'

Dave already suggested how you could write part of .__format__ to make 
the latter be real also.

-- 
Terry Jan Reedy

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


Thread

Controlling number of zeros of exponent in scientific notation faraz@squashclub.org - 2013-03-05 12:09 -0800
  Re: Controlling number of zeros of exponent in scientific notation Dave Angel <davea@davea.name> - 2013-03-05 15:56 -0500
  Re: Controlling number of zeros of exponent in scientific notation Terry Reedy <tjreedy@udel.edu> - 2013-03-06 00:45 -0500
  Re: Controlling number of zeros of exponent in scientific notation Roy Smith <roy@panix.com> - 2013-03-06 09:03 -0500
    Re: Controlling number of zeros of exponent in scientific notation jmfauth <wxjmfauth@gmail.com> - 2013-03-06 07:16 -0800
  Re: Controlling number of zeros of exponent in scientific notation "Russ P." <Russ.Paielli@gmail.com> - 2013-03-06 11:11 -0800

csiph-web