Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert exponential value to string format in python?

I'm doing some calculations which give very small decimal numbers for example, 0.0000082

When I'm saving it in a variable, it changes into exponent form. I need the result as a string in the end. So, converting the result using str() is not possible because it keeps the e in the string. I need the string to have exactly 8 decimal places. Is there any way to do this while keeping the 8 digit precision intact?

Another example: 5.8e-06 should be converted to '0.00000580' The trailing zero in the final string is not important. I need the string to be used elsewhere. So, this shouldn't be done in the print() function.

like image 978
aste123 Avatar asked Aug 22 '17 17:08

aste123


People also ask

How do you format exponential values in Python?

Use the format() Function to Represent Values in Scientific Notation in Python. Here . 1E is the specified formatting pattern. E indicates exponential notation to print the value in scientific notation, and .


1 Answers

The exponential notation is not an inherent property of the number (which is stored as a binary floating point value). It's just the default representation when converting the number to a string with str. You can specify your own formatting options if you convert the number to a string using the format function. Try something like this:

format(5.8e-06, '.8f')

The 8 in the format specifier tells it to use eight digits of precision, while the f requests it to be written as a plain decimal without exponential notation. You can read more about the format notations in the documentation.

like image 131
Blckknght Avatar answered Sep 28 '22 20:09

Blckknght