Python - String Format floats

Introduction

The %e, %f, and %g formats display floating-point numbers in different ways:

  • %E is the same as %e but the exponent is uppercase,
  • %g chooses formats by number content: use exponential format e if the exponent is less than -4 or not less than precision, and decimal format f otherwise, with a default total digits precision of 6:

Demo

x = 1.23456789 
print( x )                                    # Shows more digits before 2.7 and 3.1 
# from   w ww.  j  a  v a  2 s  . com
print( '%e | %f | %g' % (x, x, x) )
print( '%E' % x )

Result

For floating-point numbers, you can specify left justification, zero padding, numeric signs, total field width, and digits after the decimal point.

You might get by with simply converting to strings with a %s format expression or the str built-in function:

Demo

x = 1.23456789 
print( '%-6.2f | %05.2f | %+06.1f' % (x, x, x) )
print( '%s' % x, str(x) )

Result

When sizes are not known until runtime, you can use a computed width and precision by specifying them with a * in the format string.

It will use their values from the next item in the inputs to the right of the % operator-the 4 in the tuple here gives precision:

Demo

print( '%f, %.2f, %.*f' % (1/3.0, 1/3.0, 4, 1/3.0) )

Result

Related Topic