Search code examples
variablesprecisionpython-2.xepochmilliseconds

Variable always gets rounded to 2 decimal places - Python


I am getting a float number from a 2D array and the number is shown as 1406711403.588 in the array when I debugged through it. I get the variable like this

t = array_name[0][0]

and the t became 1406711403.59 no matter what format or round method I used it always like this. I tried it in terminal:

>>> t = round(1406711403.588, 3)
>>> print t
1406711403.59
>>> t = round(1406711403.588, 2)
>>> print t
1406711403.59
>>> round(1406711403.588, 3)
1406711403.588
>>> 

Why it always round it to 2 decimal places ? How can I keep the original precision ?

Many thanks !


Solution

  • This has to do with print and not round. Try this:

    >>> round(1406711403.588, 3)
    1406711403.5880001
    >>> print round(1406711403.588, 3)
    1406711403.59
    

    print will do that rounding automatically unless you specify something else. You can specify the number of decimal points like so:

    >>> print "%.3f" % (round(1406711403.588, 3))
    1406711403.588
    >>> print "%.5f" % (round(1406711403.588, 3))
    1406711403.58800