Controlling number of zeros of exponent in scientific notation

Terry Reedy tjreedy at udel.edu
Wed Mar 6 06:45:10 CET 2013


On 3/5/2013 3:09 PM, faraz at 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




More information about the Python-list mailing list