Print numbers in terms of engineering units in Python [duplicate]

爱⌒轻易说出口 提交于 2019-12-24 07:03:23

问题


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



来源:https://stackoverflow.com/questions/12985438/print-numbers-in-terms-of-engineering-units-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!