Search code examples
pythonpython-2.7scientific-notation

Convert to scientific notation, Python 2.7


print "= ", W_ / 1000, "m^3/min"

Currently this shows up as 0.001 m^3/min How do I make it display as 1.000e-03 m^3/min?


Solution

  • Use string formatting, which gives you all the control you need over the formatting of floating point values:

    print '= {:.3e} m^3/min'.format(W_ / 1000)
    

    The .3 is the precision (3 decimal digits), the e tells the floating point object to use scientific notation.

    Note that I only needed to create one string, and the {..} form a placeholder where the first argument passed to the str.format() method is inserted.

    Demo:

    >>> W_ = 1.0
    >>> print '= {:.3e} m^3/min'.format(W_ / 1000)
    = 1.000e-03 m^3/min