Welcome, guest | Sign In | My Account | Store | Cart

eng(x) returns a string representing x using the "engineering notation"

Python, 18 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# -*- coding: utf-8 -*-
"""
Created on Wed April 15th 2015

"""

from decimal import Decimal

def eng(num):
   return Decimal(num).normalize().to_eng_string() 
    
if __name__ == '__main__':
        
    test = [-78951,-500,1e-3,0.005,0.05,0.12,10,23.3456789,50,150,250,800,1250,
            127e11,51234562]
        
    for x in test:
         print "%s: %s " % (x,eng(x))
        

This is an alternative method to the another recipe on this site. By using a library method in the decimal module, it uses less code, but also doesn't work in as many cases.

The original method is linked as this recipe's parent.

1 comment

mai3a 8 years, 7 months ago  # | flag

so few lines and so many errors. here's the real deal, no lint errors:

-- coding: utf-8 --

""" Created 2015 """

from decimal import Decimal

TTT uppercase makes it a list var

this just demonstrates the normalize-function

and will print some numbers in a loop

the Spyder IDE will run it no problem.

def eng(num): """ some doc string right here """ return Decimal(num).normalize().to_eng_string()

if __name__ == '__main__':

TTT = [-78951, -500, 1e-3, 0.005, 0.05, 0.12,
           10, 23.3456789, 50, 150, 250, 800, 1250,
           127e11, 51234562]

for x in TTT:
    print "%s: %s " % (x, eng(x))
no lint errors in here