convert exponential to decimal in python

喜欢而已 提交于 2019-12-01 02:49:43

问题


I have an array in python that contains a set of values, some of them are

2.32313e+07

2.1155e+07

1.923e+07

11856

112.32

How do I convert the exponential formats to the decimal format

Additional: Is there a way I can convert the exponent directly to decimal when printing out in UNIX with awk?


回答1:


I imagine you have a list rather than an array, but here it doesn't make much of a difference; in 2.6 and earlier versions of Python, something like:

>>> L = [2.32313e+07, 2.1155e+07, 1.923e+07, 11856, 112.32]
>>> for x in L: print '%f' % x
... 
23231300.000000
21155000.000000
19230000.000000
11856.000000
112.320000

and in 2.6 or later, the .format method. I imagine you are aware that the numbers per se, as numbers, aren't in any "format" -- it's the strings you obtain by formatting the numbers, e.g. for output, that are in some format. BTW, variants on that %f can let you control number of decimals, width, alignment, etc -- hard to suggest exactly what you may want without further specs from you.

In awk, you can use printf.




回答2:


You can use locale.format() to format your numbers for output. This has the additional benefit of being consistent with any locale-specific conventions that might be expected in the presentation of the numbers. If you want complete control at the specific place where you do the output, you'd be better of with the print "format" % vars... variant.

Example:

>>> import locale 
>>> locale.setlocale(locale.LC_ALL, "")
'C/UTF-8/C/C/C/C'
>>> locale.format("%f", 2.32313e+07, 1)
'23231300.000000'



回答3:


In answer to the last part of your question, awk can use the same printf format:

awk '{printf "%f\n",$1}' exponential_file

Where exponential_file contains:

2.32313e+07
2.1155e+07
1.923e+07
11856
112.32

You can do the conversion into a variable for use later. Here is a simplistic example:

awk '{n = sprintf("%f\n",$1); print n * 2}' exponential_file


来源:https://stackoverflow.com/questions/1573080/convert-exponential-to-decimal-in-python

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