I have a Python program where i calculate some probabilities, but in some of the answers I get f.ex. 8208e-06, but I want my numbers to come out on the regular form 0.000008... How do I do this?
Asked
Active
Viewed 2.0k times
9
-
1what do you mean come out - are you printing them and the format is unexpected? – blueberryfields Mar 31 '14 at 07:58
-
Well, yeah. The format is as described 8208e-06, but I need to be written in the "normal form". Is this possible? – user2795095 Mar 31 '14 at 08:03
-
possible duplicate of [How do I suppress scientific notation in Python?](http://stackoverflow.com/questions/658763/how-do-i-suppress-scientific-notation-in-python) – Jasper Mar 31 '14 at 08:10
1 Answers
20
You can use the f
format specifier and specify the number of decimal digits:
>>> '{:.10f}'.format(1e-10)
'0.0000000001'
Precision defaults to 6
, so:
>>> '{:f}'.format(1e-6)
'0.000001'
>>> '{:f}'.format(1e-7)
'0.000000'
If you want to remove trailing zeros just rstrip
them:
>>> '{:f}'.format(1.1)
'1.100000'
>>> '{:f}'.format(1.1).rstrip('0')
'1.1'
By default when converting to string using str
(or repr
) python returns the shortest possible representation for the given float, which may be the exponential notation.
This is usually what you want, because the decimal representation may display the representation error which user of applications usually don't want and don't care to see:
>>> '{:.16f}'.format(1.1)
'1.1000000000000001'
>>> 1.1
1.1

Bakuriu
- 98,325
- 22
- 197
- 231