Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing numbers in python

Tags:

python

I have a script that generates some numbers (specifically times in epoch form).

Everytime it generates a number, I append the number to an array (called VALUES) and print both the array and that number. However, the number does not contain as many places after the decimal as the number in the array.

For example, a sample output will look like this (after 3 iterations):

VALUES = [733948.45278935181, 733948.45280092594, 733948.45280092594]
Number = 733948.452801

The third number in the array corresponds to the value in Number.

How come they contain different number of positions after the decimal?

Off-topic: What are the numbers after the decimal called? I thought there was some mathematical term for them I just can't remember what it is.

Note: Code was in python.

like image 611
Paul Avatar asked Jul 13 '10 21:07

Paul


2 Answers

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
like image 144
Donald Miner Avatar answered Oct 23 '22 09:10

Donald Miner


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
like image 30
zvone Avatar answered Oct 23 '22 10:10

zvone