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

3
  • 2
    where's the code for writing the file? Commented Jun 20, 2012 at 18:30
  • What version of Python are you using? This is a known issue that's already fixed in the most recent versions of Python (e.g., 2.7.3); see bugs.python.org/issue13573 Commented Jun 20, 2012 at 20:47
  • Incidentally, looks like stackoverflow.com/questions/8455253 is a possible duplicate. Commented Jun 20, 2012 at 20:48

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.