Printing numbers in python

To get the precision you want, you need something like:

VALUES = [733948.45278935181, 733948.45280092594, 733948.45280092594]
for v in VALUES:
    print '%18.11f' % (v)

And the term I've always used for those digits after the decimal point is "those digits after the decimal point". :-)


When you print the list, it prints repr(x) for each x in the list.

When you print the number, it prints str(x).

For example:

>>> print 123456789.987654321
123456789.988

>>> print [123456789.987654321]
[123456789.98765433]

>>> print str(123456789.987654321)
123456789.988

>>> print repr(123456789.987654321)
123456789.98765433

When python prints out a number, it sometimes prints out more decimal places based on whether the internal method is calling repr or str (which both convert the number to a string). repr will return more decimal places, while str does not.

print calls str, so when you do print Number, it will trim it a tad. However, when you convert a list of numbers to a string when you do print VALUES, the list will internally use repr, giving it more decimal places.

In summary, depending on how it is being printed out, you will see different amounts of decimal places. However, internally, it is still the same number.

If you want to force it to use a specific number of decimal places, you can do this:

print "%.3f" % 3.1415   # prints 3.142

Tags:

Python