简体   繁体   中英

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?

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"

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM