The Python Oracle

How to suppress scientific notation when printing float values?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC M Beethoven - Piano Sonata No 3 in C 3

--

Chapters
00:00 Question
00:36 Accepted answer (Score 79)
01:01 Answer 2 (Score 163)
01:53 Answer 3 (Score 53)
02:11 Answer 4 (Score 52)
02:29 Thank you

--

Full question
https://stackoverflow.com/questions/6587...

Accepted answer links:
[details are in the docs]: https://docs.python.org/3/library/string...
[the equivalent old formatting]: http://docs.python.org/py3k/library/stdt...
[newer style formatting]: http://docs.python.org/py3k/library/stri...

Answer 2 links:
[formatted string literal]: https://docs.python.org/3/whatsnew/3.6.h...

Answer 3 links:
[''.format()]: http://docs.python.org/library/string.ht...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #floatingpoint

#avk47



ANSWER 1

Score 186


Using the newer version ''.format (also remember to specify how many digit after the . you wish to display, this depends on how small is the floating number). See this example:

>>> a = -7.1855143557448603e-17
>>> '{:f}'.format(a)
'-0.000000'

as shown above, default is 6 digits! This is not helpful for our case example, so instead we could use something like this:

>>> '{:.20f}'.format(a)
'-0.00000000000000007186'

Update

Starting in Python 3.6, this can be simplified with the new formatted string literal, as follows:

>>> f'{a:.20f}'
'-0.00000000000000007186'



ACCEPTED ANSWER

Score 81


'%f' % (x/y)

but you need to manage precision yourself. e.g.,

'%f' % (1/10**8)

will display zeros only.
details are in the docs

Or for Python 3 the equivalent old formatting or the newer style formatting




ANSWER 3

Score 61


Another option, if you are using pandas and would like to suppress scientific notation for all floats, is to adjust the pandas options.

import pandas as pd
pd.options.display.float_format = '{:.2f}'.format



ANSWER 4

Score 56


With newer versions of Python (2.6 and later), you can use ''.format() to accomplish what @SilentGhost suggested:

'{0:f}'.format(x/y)

And since PEP-498 is over 8 years old, Python 3.6 and later supports:

f'{x/y:f}'

Someone commented on printing lists, so here's a bonus 1-liner:

[f'{x:f}' for x in long_list]