简体   繁体   English

如何使用 SI 前缀(micro、milli、Mega、Giga 等)格式化数字?

[英]How do I format a number using SI prefix (micro, milli, Mega, Giga, etc)?

I have numbers that range from very small to very large, and I'd like to format them using "engineering notation" with a magnitude and a suffix:我的数字范围从非常小到非常大,我想使用带有大小和后缀的“工程符号”来格式化它们:

n.nnn S

where 1.0 <= n.nnn < 1000., and S is a metric (SI) prefix .其中 1.0 <= n.nnn < 1000.,S 是度量 (SI) 前缀 So:所以:

1234.5e+13 => 12.35P
12345678 => 12.35M
1234 => 1.234K
1.234 => 1.234
0.1234 => 123.4m
1234.5e-16 => 1.235f

etc. How can I do that, eg using Python?等我该怎么做,例如使用 Python?

(Posted here in Q&A style because I keep re-inventing this code, and others might find it helpful. Feel free to tweak it if you see improvements...) (以问答方式发布在这里,因为我一直在重新发明此代码,其他人可能会发现它很有帮助。如果您看到改进,请随时对其进行调整...)

Here is one implementation that lets you choose a long suffix (eg "peta") or a short suffix (eg "P"), and also lets you choose how many total digits are displayed (ie the precision):这是一种实现,可让您选择长后缀(例如“peta”)或短后缀(例如“P”),还可以让您选择显示的总位数(即精度):

def si_classifier(val):
    suffixes = {
        24:{'long_suffix':'yotta', 'short_suffix':'Y', 'scalar':10**24},
        21:{'long_suffix':'zetta', 'short_suffix':'Z', 'scalar':10**21},
        18:{'long_suffix':'exa', 'short_suffix':'E', 'scalar':10**18},
        15:{'long_suffix':'peta', 'short_suffix':'P', 'scalar':10**15},
        12:{'long_suffix':'tera', 'short_suffix':'T', 'scalar':10**12},
        9:{'long_suffix':'giga', 'short_suffix':'G', 'scalar':10**9},
        6:{'long_suffix':'mega', 'short_suffix':'M', 'scalar':10**6},
        3:{'long_suffix':'kilo', 'short_suffix':'k', 'scalar':10**3},
        0:{'long_suffix':'', 'short_suffix':'', 'scalar':10**0},
        -3:{'long_suffix':'milli', 'short_suffix':'m', 'scalar':10**-3},
        -6:{'long_suffix':'micro', 'short_suffix':'µ', 'scalar':10**-6},
        -9:{'long_suffix':'nano', 'short_suffix':'n', 'scalar':10**-9},
        -12:{'long_suffix':'pico', 'short_suffix':'p', 'scalar':10**-12},
        -15:{'long_suffix':'femto', 'short_suffix':'f', 'scalar':10**-15},
        -18:{'long_suffix':'atto', 'short_suffix':'a', 'scalar':10**-18},
        -21:{'long_suffix':'zepto', 'short_suffix':'z', 'scalar':10**-21},
        -24:{'long_suffix':'yocto', 'short_suffix':'y', 'scalar':10**-24}
    }
    exponent = int(math.floor(math.log10(abs(val))/3.0)*3)
    return suffixes.get(exponent, None)

def si_formatter(value):
    '''
    Return a triple of scaled value, short suffix, long suffix, or None if
    the value cannot be classified.
    '''
    classifier = si_classifier(value)
    if classifier == None:
        # Don't know how to classify this value
        return None

    scaled = value / classifier['scalar']
    return (scaled, classifier['short_suffix'], classifier['long_suffix'])

def si_format(value, precision=4, long_form=False, separator=''):
    '''
    "SI prefix" formatted string: return a string with the given precision
    and an appropriate order-of-3-magnitudes suffix, e.g.:
        si_format(1001.0) => '1.00K'
        si_format(0.00000000123, long_form=True, separator=' ') => '1.230 nano'
    '''
    scaled, short_suffix, long_suffix = si_formatter(value)

    if scaled == None:
        # Don't know how to format this value
        return value

    suffix = long_suffix if long_form else short_suffix

    if abs(scaled) < 10:
        precision = precision - 1
    elif abs(scaled) < 100:
        precision = precision - 2
    else:
        precision = precision - 3

    return '{scaled:.{precision}f}{separator}{suffix}'.format(
        scaled=scaled, precision=precision, separator=separator, suffix=suffix)

You can use Prefixed which has a float type with additional formatting options.您可以使用具有浮点类型和附加格式选项的Prefixed

>>> from prefixed import Float

>>> f'{Float(1234.5e+13):.2h}'
'12.35P'
>>> f'{Float(12345678):.2h}'
'12.35M'
>>> f'{Float(1234):.2h}'
'1.23k'
>>> f'{Float(1.234):.2h}'
'1.23'
>>> f'{Float(0.1234):.2h}'
'123.40m'
>>> f'{Float(1234.5e-16):.2h}'
'123.45f'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python plotly customdata [SI前缀d3]中的B(十亿)而不是G(千兆) - B (billions) instead of G (giga) in python plotly customdata [SI prefix d3] 如何使用python将SI单位转换为数字 - How to convert SI units to number using python 使用公制前缀格式化数字(SI 样式) - Formatting a number with a metric prefix (SI style) 在 Python 中使用工程符号(带有 SI 前缀)将浮点数转换为字符串 - Convert float number to string with engineering notation (with SI prefix) in Python 由于使用urllib.urlretrieve无法正常工作,我如何在Mega上下载文件? - How do I download file on Mega since it does not work using urllib.urlretrieve? 如何在 python 中使用 mega api 通过共享 url 列出大型公共文件夹的内容 - how can i list the contents of a mega public folder by it's shared url using mega api in python 如何使用 command_prefix='?' 创建多个命令? - How do I create multiple commands using command_prefix=‘!’? 如何在 Python 中格式化具有可变位数的数字? - How do I format a number with a variable number of digits in Python? 如何在 Python 中编写一个 for 循环以反复要求用户输入一个数字,直到他们输入一个整数(0、1、2 等)? - How do I write a for loop in Python to repeatedly ask the user to enter a number until they enter in a whole number (0, 1, 2, etc)? Pandas,我如何 append 为所有以数字开头的列名添加前缀? - Pandas, how do I append a prefix to all column name that start with a number?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM