Convert float number to string with engineering notation (with SI prefix) in Python(在 Python 中使用工程符号(带 SI 前缀)将浮点数转换为字符串)
                            本文介绍了在 Python 中使用工程符号(带 SI 前缀)将浮点数转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
                        
                        问题描述
我有一个浮点数,例如 x=23392342.1
I have a float number such as x=23392342.1
我想将其转换为带有工程符号的字符串(带公制前缀)
I would like to convert it to a string with engineering notation (with metric prefix)
http://en.wikipedia.org/wiki/Engineering_notationhttp://en.wikipedia.org/wiki/Metric_prefix
所以在我的例子中 23392342.1 = 23.3923421E6 = 23.3923421 M (mega)
So in my example 23392342.1 = 23.3923421E6 = 23.3923421 M (mega)
我想显示 23.3923421 M
推荐答案
这是一个灵感来自 用公制前缀格式化数字?
metric.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
def to_si(d, sep=' '):
    """
    Convert number to string with SI prefix
    :Example:
    >>> to_si(2500.0)
    '2.5 k'
    >>> to_si(2.3E6)
    '2.3 M'
    >>> to_si(2.3E-6)
    '2.3 µ'
    >>> to_si(-2500.0)
    '-2.5 k'
    >>> to_si(0)
    '0'
    """
    inc_prefixes = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
    dec_prefixes = ['m', 'µ', 'n', 'p', 'f', 'a', 'z', 'y']
    if d == 0:
        return str(0)
    degree = int(math.floor(math.log10(math.fabs(d)) / 3))
    prefix = ''
    if degree != 0:
        ds = degree / math.fabs(degree)
        if ds == 1:
            if degree - 1 < len(inc_prefixes):
                prefix = inc_prefixes[degree - 1]
            else:
                prefix = inc_prefixes[-1]
                degree = len(inc_prefixes)
        elif ds == -1:
            if -degree - 1 < len(dec_prefixes):
                prefix = dec_prefixes[-degree - 1]
            else:
                prefix = dec_prefixes[-1]
                degree = -len(dec_prefixes)
        scaled = float(d * math.pow(1000, -degree))
        s = "{scaled}{sep}{prefix}".format(scaled=scaled,
                                           sep=sep,
                                           prefix=prefix)
    else:
        s = "{d}".format(d=d)
    return s
if __name__ == "__main__":
    import doctest
    doctest.testmod()
及其用法:
from metric import to_si
d = 23392342.1
print(to_si(d))
会显示
23.3923421 M
                        这篇关于在 Python 中使用工程符号(带 SI 前缀)将浮点数转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:在 Python 中使用工程符号(带 SI 前缀)将浮点数转换为字符串
				
        
 
            
        基础教程推荐
             猜你喜欢
        
	     - 求两个直方图的卷积 2022-01-01
 - Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
 - PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
 - PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
 - 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
 - 在Python中从Azure BLOB存储中读取文件 2022-01-01
 - 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
 - 包装空间模型 2022-01-01
 - 修改列表中的数据帧不起作用 2022-01-01
 - 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				