Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Floating Point Formatting

I've seen a few questions about this already, but none that I read helped me actually understand why what I am trying to do is failing.

So I have a bunch of floating point values, and they have different precisions. Some are 0.1 others are 1.759374, etc. And I want to format them so they are ALL in the form of "+0.0000000E+00" I tried doing

number = '%1.7f' % oldnumber

but that didn't work. I thought what I was telling it to do was "one digit perfor the decimal point, and 7 after, float" but it doesn't work. I'm not really getting the examples in the docs, which don't seem to even bother with "before and after decimal point" issues, and I didn't find a question that was about before and after decimal point fixing.

Now, I know that some of my numbers are 0.0437 or similar, and I want them to appear as 4.3700000E-02 or something. I was sort of hoping it would do the E bit on it's own, but if it doesn't how do I do it?

Here is the exact line I have:

RealValConv =   '%1.7g' % struct.unpack('!f',    RealVal.decode('hex'))[0]

RealVal is a hex number that represents the value I want.

Also, this is in Python 2.7

like image 250
CamelopardalisRex Avatar asked Dec 15 '22 06:12

CamelopardalisRex


1 Answers

>>> '{:.7e}'.format(0.00000000000000365913456789)
'3.6591346e-15'
like image 181
planestepper Avatar answered Dec 27 '22 12:12

planestepper