简体   繁体   English

Python浮点格式

[英]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 有些是0.1其他是1.759374等等。我想格式化它们所以它们都是“+ 0.0000000E + 00”的形式我试过做

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. 现在,我知道我的一些数字是0.0437或类似,我希望它们显示为4.3700000E-02或其他东西。 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? 我有点希望它可以自己做E位,但如果不是我怎么办呢?

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. RealVal是十六进制数,表示我想要的值。

Also, this is in Python 2.7 此外,这是在Python 2.7中

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

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). 或者,如果要控制精度,可以使用@leon方法(+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
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM