Python 转换为字符串时浮点精度丢失

Python precision of float is lost while converting to string

我正在使用 Scapy 的 sniff 函数从 pcap 文件中读取数据包。

pkt=sniff(offline="a.pcap",count=1)[0]

pkt.time 的 IDLE 中,我能够获得数据包的时间戳,即 1431063004.998014。但是,当我尝试将时间戳转换为带有 str(pkt.time)pkt.time 的字符串时,我给出 print pkt.time,我只得到 1431063005.0.

是否可以获取字符串形式的准确时间戳值??

注:
我查看了 decimal 模块。但这需要精确数字。我想,如果不知道位数,那将无济于事。

试试这个:

  "{:.6f}".format(pkt.time)

repr 是另一种类似于 str 的方法,它可以精确转换整个浮点数。无需导入 decimal 或任何东西。就像使用 str 一样使用它,它只是 returns 一个 str 对象。

>>> x = repr(pkt.time)
>>> type(x)
>>> <type 'str'>

试试这个:

"{:.6f}".format(pkt.time)