How to print floating point in scientific format?

Ben Finney bignose-hates-spam at and-benfinney-does-too.id.au
Fri Aug 8 20:36:32 EDT 2003


On 8 Aug 2003 12:15:53 -0700, sdhyok wrote:
> I want to change the DEFAULT behavior of python

Then you can modify the Python source to do whatever you want.  This is
a bad idea for your current stated purpose, though.

Changing the default behaviour of a native Python type will only be
local to machines that have this altered Python; if you write code that
depends on that, it will break unexpectedly on other machines.

> to print out all floating points in scientific format?
> For instance,
> 
>>x=0.01
>>print x
> 1.000000E-2 #Like print "%E"%x
> 
> How can I do it?

Since changing the way native flot object operate is a bad idea, two
ways seem reasonable.

One is to always use output formatting, since it will make your code
clearer.

    >>> x = 0.01
    >>> print "%E" % x
    1.000000E-02

The other way is to subclass the 'float' class to overload its __str__
method.  This gives you objects that default to what you want, without
breaking Python.

    >>> class SciFloat( float ):
    ...     """ A floating-point number class
    ...         that defaults to scientific representation
    ...     """
    ...     def __init__( self, *args, **kwargs ):
    ...         float.__init__( self, args, kwargs )
    ...         return
    ...     def __str__( self ):
    ...         return "%E" % self
    ... 
    >>> if( __name__ == '__main__' ):
    ...     x = SciFloat( 0.01 )
    ...     print x
    ... 
    1.000000E-02
    >>> 

-- 
 \       "I filled my humidifier with wax. Now my room is all shiny."  |
  `\                                                  -- Steven Wright |
_o__)                                                                  |
Ben Finney <http://bignose.squidly.org/>




More information about the Python-list mailing list