[Tutor] How to print numbers in scientific notation form?

Cédric Lucantis omer at no-log.org
Sat Jun 28 15:17:03 CEST 2008


Le Saturday 28 June 2008 14:55:04 Dick Moores, vous avez écrit :
> %.4g comes close to what I want, but no cigar. In the examples below,
> the first 2 are not scientific notation form.
>
>  >>> print "%.4g" % 5.09879870978
>
> 5.099
>
>  >>> print "%.4g" % .0009874345
>
> 0.0009874
>
>  >>> print "%.4g" % .000009878
>
> 9.878e-006
>
>  >>> print "%.4g" % 187686876876238746
>
> 1.877e+017
>
> How can I print all numbers in scientific notation form, and
> designate the number of significant digits?

%g automatically choose the more readable form. Use %e for that:

>>>> '%e' % 1.0
'1.000000e+00'

and to set the number of significant digits (it seems to only set the number 
of digits after the comma, so you have to subtract 1 from it) :

>>> '%.3e' % 1.0
'1.000e+00'

-- 
Cédric Lucantis


More information about the Tutor mailing list