0

I have a normal float number such as "1234.567" or "100000". I would like to convert it to a string such that the precision is fixed and the number is in scientific notation. For example, with 5 digits, the results would be "1.2346e003 and "1.0000e005", respectively. The builtin Decimal number -> string functions will round it if it can, so the second number would be only "1e005" even when I want more digits. This is undesirable since I need all numbers to be the same length.

Is there a "pythonic" way to do this without resorting to complicated string operations?

3 Answers 3

1
precision = 2 number_to_convert = 10000 print "%0.*e"%(precision,number_to_convert) 

is that what you are asking for?

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the %e string formatter:

>>> '%1.5e'%1234.567 '1.23457e+03' >>> "%1.5e"%100000 '1.00000e+05' 

%x.ye where x = min characters and y = max precision.

2 Comments

ahhh you fixed it before I posted ... (+1)
Yeah I missed the same length part for whatever reason. All good thx.
1

If you need to keep the 3-digit exponent like in your example, you can define your own function. Here's an example adapted from this answer:

def eformat(f, prec, exp_digits): s = "%.*e"%(prec, f) mantissa, exp = s.split('e') return "%se%0*d"%(mantissa, exp_digits, int(exp)) >>> print eformat(1234.567, 4, 3) 1.2346e003 

1 Comment

yes a three digit is good because 1e200 is not longer than 1e20.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.