用Python中的工程单位打印数字 [英] Print numbers in terms of engineering units in Python

查看:48
本文介绍了用Python中的工程单位打印数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
以工程格式打印编号

如何以科学计数法打印数字的幂是3的倍数?例如:

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

我正在寻找类似于计算器上 ENG 按钮的功能.某个地方有Python软件包可以做到这一点吗?

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

推荐答案

似乎还没有这样的功能(至少在Python 2.7中如此),请参见: http://bytes.com/topic/python/answers/616948-string-formatting-engineering-notation 我找到了以下解决方案(我个人不太喜欢,但似乎可行):

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.

也请点击此处以工程格式打印编号

这篇关于用Python中的工程单位打印数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆