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?

有帮助吗?

解决方案

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top