Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid e-05 in python

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?

like image 991
user2795095 Avatar asked Mar 31 '14 07:03

user2795095


People also ask

How do I print numbers without E in Python?

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 do you stop scientific notation when printing float values?

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.


1 Answers

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
like image 67
Bakuriu Avatar answered Oct 02 '22 06:10

Bakuriu