Skip to content Skip to sidebar Skip to footer

How To Write Real Value Of -2.12683575e-04 In A File (python)

I am currently working with really tiny values and when I try to write a value like -0.000212683575 in a file, it write me -2.12683575e-04. The problem is that I would like to have

Solution 1:

Python allows you to choose formats. For example, this gives the scientific notation that you don't want:

>>>x =  -0.00021268357>>>'{:.2e}'.format(x)
'-2.13e-04'

But, this format gives the decimal notation that you prefer:

>>> '{:.9f}'.format(x)
'-0.000212684'

We can use these formats when we write to a file:

>>>withopen('output', 'w') as f:...    f.write('{:.9f}'.format(x))...>>>open('output').read()
'-0.000212684'

You can read about the format method, and all its complex and powerful features, here.

Python also offers printf style formatting. For example:

>>> '%f' % x
'-0.000213'>>> '%e' % x
'-2.126836e-04'

Solution 2:

While writing a number in a file, you can write it as a string and it'll be all you need. ex:

>>>num = -0.000212683575>>>f = open("a.txt","w")>>>f.write(str(num))>>>f.close()>>>open("a.txt","r").read()
'-0.000212683575'
>>>

Post a Comment for "How To Write Real Value Of -2.12683575e-04 In A File (python)"