3

Can anyone tell me what happened when str(time.time()) runs? It seems the data has been truncated, but it recovered when float(str(time.time())) runs. I'm so confused.

In [1]: import time

In [2]: a = time.time()

In [3]: a
Out[3]: 1445007755.321532

In [4]: str(a)
Out[4]: '1445007755.32'

In [6]: a.__str__()
Out[6]: '1445007755.32'

In [7]: float(a)
Out[7]: 1445007755.321532
2

2 Answers 2

1

Calling str(a) does not modify a, so there is no reason why float(a) should depend on str(a). Maybe you wanted to reassign a?

a = 1445007755.321532
a = str(a)
float(a)

In this case the result is different:

>>> a = 1445007755.321532
>>> b = str(a)
>>> a == float(b)
False
>>> a, b, float(b)
(1445007755.321532, '1445007755.32', 1445007755.32)

Note that it holds that float(x) == x if x is already a float, so what you see is not surprising at all.

Even more: float(x) is x if x is of type float.

If you wonder why str seems to truncate the number it is because it returns a "human readable" representation of the value as a string.

If you want an "exact" representation use repr, or simply use a proper formatting function like: "%.6f" % a to control the number of decimal digits etc.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I also find a post here, stackoverflow.com/questions/1436703/… , which will be valuable for this answer, thanks a again. @Bakuriu
0

The difference in the number of digits after the decimal point is the difference between str(f) and repr(f).

By default, the values are converted to string (before displaying in the ipython console), using repr():

In [1]: class C:
   ...:     def __str__(self):
   ...:         return 'str'
   ...:     def __repr__(self):
   ...:         return 'repr'
   ...:     

In [2]: C()
Out[2]: repr

In [3]: str(C())
Out[3]: 'str'

btw, I can't reproduce your output on Python 3.4:

In [4]: 1445007755.321532
Out[4]: 1445007755.321532

In [5]: str(1445007755.321532)
Out[5]: '1445007755.321532'

In [6]: 1445007755.321532 .__str__()
Out[6]: '1445007755.321532'

But I can reproduce it on Python 2:

In [1]: 1445007755.321532
Out[1]: 1445007755.321532

In [2]: str(1445007755.321532)
Out[2]: '1445007755.32'

In [3]: 1445007755.321532 .__str__()
Out[3]: '1445007755.32'

Note: float() does NOT restore the precision here:

In [4]: float('1445007755.32')
Out[4]: 1445007755.32

In [5]: float(1445007755.32)
Out[5]: 1445007755.32

float(a) shows more digits in your question because a is already a float (it is probably a noop operation because floats are immutable):

In [6]: a = 1445007755.321532

In [7]: a is float(a)
Out[7]: True

i.e., float(a) may return the exact same object in this case.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.