Python Decimal - engineering notation for mili (10e-3) and micro (10e-6)

前端 未结 5 1342
情话喂你
情话喂你 2021-01-01 23:53

Here is the example which is bothering me:

>>> x = decimal.Decimal(\'0.0001\')
>>> print x.normalize()
>>> print x.normalize().to_         


        
5条回答
  •  悲&欢浪女
    2021-01-02 00:31

    EDIT: Matplotlib implemented the engineering formatter, so one option is to directly use Matplotlibs formatter, e.g.:

    import matplotlib as mpl
    formatter = mpl.ticker.EngFormatter()
    formatter(10000)
    
    result: '10 k'
    

    Original answer:

    Based on Julian Smith's excellent answer (and this answer), I changed the function to improve on the following points:

    • Python3 compatible (integer division)
    • Compatible for 0 input
    • Rounding to significant number of digits, by default 3, no trailing zeros printed

    so here's the updated function:

    import math
    def eng_string( x, sig_figs=3, si=True):
        """
        Returns float/int value  formatted in a simplified engineering format -
        using an exponent that is a multiple of 3.
    
        sig_figs: number of significant figures
    
        si: if true, use SI suffix for exponent, e.g. k instead of e3, n instead of
        e-9 etc.
        """
        x = float(x)
        sign = ''
        if x < 0:
            x = -x
            sign = '-'
        if x == 0:
            exp = 0
            exp3 = 0
            x3 = 0
        else:
            exp = int(math.floor(math.log10( x )))
            exp3 = exp - ( exp % 3)
            x3 = x / ( 10 ** exp3)
            x3 = round( x3, -int( math.floor(math.log10( x3 )) - (sig_figs-1)) )
            if x3 == int(x3): # prevent from displaying .0
                x3 = int(x3)
    
        if si and exp3 >= -24 and exp3 <= 24 and exp3 != 0:
            exp3_text = 'yzafpnum kMGTPEZY'[ exp3 // 3 + 8]
        elif exp3 == 0:
            exp3_text = ''
        else:
            exp3_text = 'e%s' % exp3
    
        return ( '%s%s%s') % ( sign, x3, exp3_text)
    

提交回复
热议问题