本文介绍了Python浮点格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了一些关于这方面的问题,但没有一个我读了帮助我真正理解为什么我想要做的是失败。



有一堆浮点值,他们有不同的精度。有些是0.1其他的是1.759374等,而我想格式化它们,所以他们都是+ 0.0000000E + 00的形式我试着做

pre > number ='%1.7f'%oldnumber

工作。我以为我说的是小数点后一位数字,后面是7位数字,但是它不起作用。我没有真正得到文档中的例子,这似乎甚至没有小数点前后的问题的困扰,我没有发现一个小数点修复前后的问题。 p>

现在,我知道我的一些数字是0.0437或类似的,我希望他们出现在4.3700000E-02之类的东西。我有点希望它能自己做E,但是如果不是我该怎么做?

下面是我的确切线:

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

RealVal是一个十六进制数字,代表我想要的值。
$ b

此外,这是在Python 2.7中的解决方案

'3.6591346e-15'


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

解决方案
>>> '{:.7e}'.format(0.00000000000000365913456789)
'3.6591346e-15'

这篇关于Python浮点格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 03:57