Converting 5.223701009526849e-05 to 5e-05
Cecil Westerhof
Cecil at decebal.nl
Sun May 3 04:11:44 EDT 2015
When I have a value like 5.223701009526849e-05 in most cases I am not
interested in all the digest after the dot. Is there a simple way to
convert it to a string like '5e-05'?
I could do something like:
def format_small_number(n):
abs_n = abs(n)
assert (abs_n < 1) and (abs_n > 0)
length = len(str(int(1 / abs_n)))
if length <= 4:
return '{0}'.format(int(n * 10 ** length) / 10.0 ** length)
else:
return '{0}E-{1}'.format(int(n * 10 ** length), length)
I use '5E-5' because I prefer that above '5e-5'.
I should take care of rounding: now 0.9999 becomes 0.9.
But I was wondering if there is a better way.
--
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
More information about the Python-list
mailing list