Python Floating Point Formatting

Deadly 提交于 2019-12-10 17:55:31

问题


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


回答1:


>>> '{:.7e}'.format(0.00000000000000365913456789)
'3.6591346e-15'



回答2:


You can use the scientific notation format: Something like this:

number = '%e' % oldnumber

>>> x = 1.759374
>>> print '%e' % x
1.759374e+00
>>>
>>> x = 1.79
>>> print '%e' % x
1.790000e+00
>>>
>>> x = 1.798775655
>>> print '%e' % x
1.798776e+00
>>>

Or, if you want to control precision, you can use the format method as sugged by @leon approach (+1).

>>> x = 1.759374
>>>
>>> print('{:.2e}'.format(x))
1.76e+00
>>>
>>> print('{:.10e}'.format(x))
1.7593740000e+00
>>>
>>> print('{:.4e}'.format(x))
1.7594e+00
>>>


来源:https://stackoverflow.com/questions/18709000/python-floating-point-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!