Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #89834
| From | Cecil Westerhof <Cecil@decebal.nl> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Converting 5.223701009526849e-05 to 5e-05 |
| Organization | Decebal Computing |
| Date | 2015-05-03 10:11 +0200 |
| Message-ID | <87vbgakrlr.fsf@Equus.decebal.nl> (permalink) |
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
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Converting 5.223701009526849e-05 to 5e-05 Cecil Westerhof <Cecil@decebal.nl> - 2015-05-03 10:11 +0200
Re: Converting 5.223701009526849e-05 to 5e-05 Ben Finney <ben+python@benfinney.id.au> - 2015-05-03 18:40 +1000
Re: Converting 5.223701009526849e-05 to 5e-05 Cecil Westerhof <Cecil@decebal.nl> - 2015-05-03 11:22 +0200
Re: Converting 5.223701009526849e-05 to 5e-05 Chris Angelico <rosuav@gmail.com> - 2015-05-03 19:51 +1000
Re: Converting 5.223701009526849e-05 to 5e-05 Cecil Westerhof <Cecil@decebal.nl> - 2015-05-03 12:02 +0200
Re: Converting 5.223701009526849e-05 to 5e-05 Chris Angelico <rosuav@gmail.com> - 2015-05-03 20:57 +1000
Re: Converting 5.223701009526849e-05 to 5e-05 Dave Angel <davea@davea.name> - 2015-05-03 07:34 -0400
Re: Converting 5.223701009526849e-05 to 5e-05 Ben Finney <ben+python@benfinney.id.au> - 2015-05-03 18:48 +1000
Re: Converting 5.223701009526849e-05 to 5e-05 Alexander Blinne <news@blinne.net> - 2015-05-07 10:00 +0200
csiph-web