Python Decimal - engineering notation for mili (10e-3) and micro (10e-6) -
here example bothering me:
>>> x = decimal.decimal('0.0001') >>> print x.normalize() >>> print x.normalize().to_eng_string() 0.0001 0.0001
is there way have engineering notation representing mili (10e-3) , micro (10e-6)?
here's function things explicitly, , has support using si suffixes exponent:
def eng_string( x, format='%s', si=false): ''' returns float/int value <x> formatted in simplified engineering format - using exponent multiple of 3. format: printf-style string used format value before exponent. si: if true, use si suffix exponent, e.g. k instead of e3, n instead of e-9 etc. e.g. format='%.2f': 1.23e-08 => 12.30e-9 123 => 123.00 1230.0 => 1.23e3 -1230000.0 => -1.23e6 , si=true: 1230.0 => 1.23k -1230000.0 => -1.23m ''' sign = '' if x < 0: x = -x sign = '-' exp = int( math.floor( math.log10( x))) exp3 = exp - ( exp % 3) x3 = x / ( 10 ** exp3) if si , exp3 >= -24 , exp3 <= 24 , exp3 != 0: exp3_text = 'yzafpnum kmgtpezy'[ ( exp3 - (-24)) / 3] elif exp3 == 0: exp3_text = '' else: exp3_text = 'e%s' % exp3 return ( '%s'+format+'%s') % ( sign, x3, exp3_text)
Comments
Post a Comment