Jefferson Hudson
Jefferson Hudson

Reputation: 738

Printing floating point in python

Check out this code:

>>> print "var: %g" % 3.12345678
var: 3.12346
>>> print "var: %G" % 3.12345678
var: 3.12346
>>> print "var: %e" % 3.12345678
var: 3.123457e+00
>>> print "var: %E" % 3.123456
var: 3.123457E+00

Why don't all the digits get displayed?

Why does the 6 get dropped from scientific notation?

Upvotes: 0

Views: 70

Answers (2)

CT Zhu
CT Zhu

Reputation: 54380

see: http://docs.python.org/2/library/stdtypes.html the default precision of %g and %G is 6, so it only output 6 digits (truncated).

for exponential format, the default precision is 6 digits AFTER decimal point, and it is rounded (to 3.123457)

Upvotes: 0

Patrick Lorio
Patrick Lorio

Reputation: 5668

Use %.nf where n is the number of sig-figs

print 'var: %.10f' % 3.12345678
# outputs: "var: 3.1234567800"

print 'var: %.10E' % 3.12345678
# outputs: "var: 3.1234567800E+00"

print 'var:', 3.12345678
# outputs: "var: 3.12345678"

Upvotes: 1

Related Questions