Converting 5.223701009526849e-05 to 5e-05

Ben Finney ben+python at benfinney.id.au
Sun May 3 04:40:38 EDT 2015


Cecil Westerhof <Cecil at decebal.nl> writes:

> When I have a value like 5.223701009526849e-05 in most cases I am not
> interested in all the digest after the dot.

What type of value is it?

A ‘float’ value has many different textual representations, most of them
inaccurate. So talking about the digits of a ‘float’ value is only
partly meaningful; digits are a property of some chosen representation,
not intrinsic to the number.

A ‘str’ value can be converted in various ways, but is useless as a
number until you create a new number from the result.

Choosing a solution will rely on understanding that the textual
representation of a number is not itself a number; and vice versa, a
number value does not have a canonical text representation.

> Is there a simple way to convert it to a string like '5e-05'?

Assuming we're talking about a ‘float’ value::

    >>> foo = 5.223701009526849e-05
    >>> "{foo:5.1}".format(foo=foo)
    '5e-05'

See the ‘str.format’ documentation, especially the detailed
documentation for the “format specification mini-language”
<URL:https://docs.python.org/3/library/string.html#format-specification-mini-language>
for how to specify exactly how you want values to be formatted as
text.

-- 
 \         “The double standard that exempts religious activities from |
  `\       almost all standards of accountability should be dismantled |
_o__)                   once and for all.” —Daniel Dennett, 2010-01-12 |
Ben Finney




More information about the Python-list mailing list