简体   繁体   中英

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.

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 .

另一个想法:

'{0:.7f}'.format(0.0000082)

you can try with :

import decimal

print(str(decimal.Decimal(5.8e-06))[:10])

>>> 0.00000580
print ("{:.6f}".format(1e-4))

将打印出来

0.000100

You could use print:

>>> number = 1e-08
>>> number
1e-08
>>>print("{:.12f}".format(float(number)))
0.000000010000

or You could convert number and store it in string:

>>> str1 = "{:.12f}".format(float(number))
>>> str1
'0.000000010000'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM