Print numbers in terms of engineering units in Pyt

2019-07-31 07:50发布

问题:

Possible Duplicate:
Print number in engineering format

How do I print numbers in scientific notation with powers that are multiples of 3? For example:

1.5e4      --> 15e3
1.27e-8    --> 12.7e-9
2.9855e-11 --> 29.855e-9

I'm looking for a function similar to the ENG button on a calculator. Is there a Python package somewhere that does this?

回答1:

It appears there isn't such a feature yet (at least in Python 2.7), see: http://bugs.python.org/issue8060 On the page http://bytes.com/topic/python/answers/616948-string-formatting-engineering-notation I found the following solution (which I personally don't like that much, but seems to work):

import math

for exponent in xrange(-10, 11):
    flt = 1.23 * math.pow(10, exponent)
    l = math.log10(flt)
    if l < 0:
        l = l - 3
    p3 = int(l / 3) * 3
    multiplier = flt / pow(10, p3)
    print '%e =%fe%d' % (flt, multiplier, p3)

Just adapt it according to your needs.

EDIT: Please look here, too Print number in engineering format