2

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. 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

mskfisher
  • 3,291
  • 4
  • 35
  • 48
code
  • 5,294
  • 16
  • 62
  • 113

2 Answers2

3

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. 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
Russell Borogove
  • 18,516
  • 4
  • 43
  • 50
1

You can convert the number to a string using any appropriate method and write the string to the CSV.

>>> x = 17510.3889778429
>>> s = str(x)
>>> s
'17510.3889778'
>>> s = '%17.11f' % x
>>> s
'17510.38897784290'
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622