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?
The best way to print even small float numbers is to use f-strings, i.e., special types of formatting string that are enclosed in f'...' . Within a given f-string, you can use the {...:. 12f} format specifier to tell Python to use floating point precision with 12 digits after the decimal point.
How to suppress scientific notation when printing float values? There is a simple technique to suppress scientific notation when using float values by using the %f flag in string. This will convert the number into a floating-point number and then print it. Note that this method has a precision of 10^-6 only.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With