简体   繁体   中英

Python float to string (scientific notation), in specific format

This is a very specific question, but despite a large number of online resources I cannot seem to find a function which does what I want. Assume I have an arbitrary float, say for example "2.". I want to convert the float into the following format:

'2.000000E+000'

That is to say: 8 digits before the exponential, and 3 digits (four counting the sign) after the exponential. There are a few functions which almost (but not quite) yield the desired output. Using

"%.6e" %float(2)

yields the output

'2.000000e+00'

Which permits me to specify how many digits I have to before the exponential, but not after - it always gives me two digits. The function numpy.format_float_scientific, on the other hand:

numpy.format_float_scientific(2.0000000000, exp_digits=3,precision=6)
Out[30]: '2.e+000'

permits me to specify the number of digits after the exponential, but not before. I would like to do both. Do you know how I could achieve this?

You can try with unique to False for numpy :

numpy.format_float_scientific(2.0000000000, unique=False, exp_digits=3,precision=6)

Output:

'2.000000e+000'

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