[英]Python Output to File Higher Floating Point Precision
The following: 下列:
>>>import struct
>>>struct.unpack('!d', ('40d11998e5035288').decode('hex'))[0]
>>>
>>>17510.3889778429
I would like to be able to print the value 17510.3889778429 to a .csv output file. 我希望能够将值17510.3889778429打印到.csv输出文件。 For some reason, when I write this to a file, it rounds the decimal and only writes:
出于某种原因,当我将其写入文件时,它会舍入小数并且只会写入:
17510.3889778
How would I print this with higher precision? 如何以更高的精度打印?
Thanks, Ned 谢谢,奈德
Assuming you're using Python's csv module, the documentation says that non-string data is formatted using str()
, and that seems to be where the truncation is happening. 假设您正在使用Python的csv模块,文档说非字符串数据使用
str()
格式化,这似乎是截断发生的地方。 So one thing you could do is define your own class that stringizes the way you want: 所以你可以做的一件事就是定义你自己的类,按照你想要的方式进行字符串化:
class myFloat( float ):
def __str__(self):
return "%.12f"%self
x = myFloat( 17510.3889778429 )
print "%s"%x
Yields: 产量:
17510.388977842900
You can convert the number to a string using any appropriate method and write the string to the CSV. 您可以使用任何适当的方法将数字转换为字符串,并将字符串写入CSV。
>>> x = 17510.3889778429
>>> s = str(x)
>>> s
'17510.3889778'
>>> s = '%17.11f' % x
>>> s
'17510.38897784290'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.