# eng_alpha.py # def eng (F = 0, fmt = "%f"): """ Formats a floating point number (F) according to the format provided (fmt). Tries to use engineering notation (i.e. the exponent is in powers of three). Dean Provins, June, 2010 """ LExp = ['0','1','2','m',' ',' ','mu',' ',' ','n',' ',' ','p'] HExp = ['0',' ',' ','k',' ',' ','M',' ',' ','G',' ',' ','T'] f = abs (F) n = 0 s = +1 if F < 0: s = -1 if f != 0: if f >= 1.: while (f >= 100): f /= 10. n += 1 f *= 10. n -= 1 while (n % 3): n += 1 f /= 10. else: while (f < 99): f *= 10. n -= 1 while (n % 3): n += 1 f /= 10. # Uncomment these if you want a leading '0.' #f /= 10. #n += 1 #S = fmt % (s * f, n) # store this result in a cell if F < 1: if s > 0: return fmt % (f) + LExp[-s * n] # return the formatted string to store in a cell else: return fmt % (s * f) + LExp[s * n] else: return fmt % (s * f) + HExp[n * s] # ---------end of the function --------- if __name__ == "__main__": # Some tests... Try them by running "python eng.py" print "some tests" print "----------" print "0:", eng () print print "1.:", eng (1.) print "1.23:", eng (1.23) print "123:", eng (123) print "1234.567:", eng (1234.567) print print "11:", eng (11) print print "* * * Less than One Positive * * * " print print "0.4:", eng (0.4) print "0.0004:", eng (0.0004) print "0.0000004:", eng (0.0000004) print print "0.004:", eng (0.004) print # print "0.001234567E-7:", eng (0.001234567E-7) print "6,000,000:", eng (6000000) print "6,000,000,000:", eng (6000000000) print "6,000,000,000,000:", eng (6000000000000) print print "* * * * < 1,000, > 1 * * * * * * * * * * " print "111:", eng (111) print "222:", eng (222) print "333:", eng (333) print "444:", eng (444) print "555:", eng (555) print "666:", eng (666) print "777:", eng (777) print "888:", eng (888) print "999:", eng (999) print print "* * * * * * Negatives! * * * * * * * * " print print "-111:", eng (-111) print "-222:", eng (-222) print "-333:", eng (-333) print "-444:", eng (-444) print "-555:", eng (-555) print "-666:", eng (-666) print "-777:", eng (-777) print "-888:", eng (-888) print "-999:", eng (-999) print print "* * * * * Less than One Negative* * * " print print "-0.4:", eng (-0.4) print "-0.0004:", eng (-0.0004) print "-0.0000004:", eng (-0.0000004) print "-0.0000000004:", eng (-0.0000000004) print print "-0.004:", eng (-0.004) print print "* * * * * * Just over One Thousand * * * * " print print "1111:", eng (1111) print "2222:", eng (2222) print "3333:", eng (3333) print "4444:", eng (4444) print "5555:", eng (5555) print "6666:", eng (6666) print "7777:", eng (7777) print "8888:", eng (8888) print "9999:", eng (9999)