Py学习  »  问与答

float 转 str 少了一位

olivetree • 9 年前 • 3278 次点击  

大家可以运行以下代码:

import time
t = time.time()
s = str(t)

print t
print s

#1413860881.911
#1413860881.91

可以看到 s 比 t 少了一位

可以发现,大的float 转换成 str 时会有问题,小的不会,再大一点的:

f = 141386088111.91
print str(f)

# 1.41386088112e+11

说了这么多,现在问题来了,python 是怎么把 float 转换成 str 的?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/713
 
3278 次点击  
文章 [ 1 ]  |  最新文章 9 年前
Py站长
Reply   •   1 楼
Py站长    9 年前

Some form of rounding is often unavoidable when dealing with floating point numbers. This is because numbers that you can express exactly in base 10 cannot always be expressed exactly in base 2 (which your computer uses).

float在计算机里存储时是二进制的,存在精度问题,因此 float和string 在转换时有精度的损失

http://stackoverflow.com/questions/1317558/python-converting-a-float-to-a-string-without-rounding-it