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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | ```
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 08 15:49:13 2012
@author: Cambium
"""
from math import *
def powerise10(x):
""" Returns x as a * 10 ^ b with 0<= a <10
"""
if x == 0: return 0 , 0
Neg = x <0
if Neg : x = -x
a = 1.0 * x / 10**(floor(log10(x)))
b = int(floor(log10(x)))
if Neg : a = -a
return a ,b
def eng(x):
"""Return a string representing x in an engineer friendly notation"""
a , b = powerise10(x)
if -3<b<3: return "%.4g" % x
a = a * 10**(b%3)
b = b - b%3
return "%.4g*10^%s" %(a,b)
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,powerise10(x))
for x in test:
print "%s: %s " % (x,eng(x))
``` |

If you are an engineer and live in the SI world, you tend to think in kilo, mega, micro etc and tend to write big or small numbers as x = a * 10^(3*n) where n is an integer. For instance 35 535 becomes 35.5 * 10^3 and 0.00052 becomes 520 * 10^-6.

I have written this two small functions so that when I use Ipython as a calculator 362645753 or 3.626e8 can be transformed into 362.6* 10^6 in a few keystrokes which is much easier on my eyes!

I am a computer user not a computer scientist, so feel free to make constructive comments.