SIfloat.py 1.5 KB
 Andreas Freise committed Dec 01, 2013 1 2 import os import re  Daniel Brown committed Feb 25, 2014 3 import pykat.exceptions as pkex  Andreas Freise committed Dec 01, 2013 4   Daniel Brown committed Feb 25, 2014 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 __suffix = {'y': 'e-24', # yocto 'z': 'e-21', # zepto 'a': 'e-18', # atto 'f': 'e-15', # femto 'p': 'e-12', # pico 'n': 'e-9', # nano 'u': 'e-6', # micro 'm': 'e-3', # mili 'c': 'e-2', # centi 'd': 'e-1', # deci 'k': 'e3', # kilo 'M': 'e6', # mega 'G': 'e9', # giga 'T': 'e12', # tera 'P': 'e15' # peta }  Andreas Freise committed Dec 01, 2013 22 def SIfloat(value):  Andreas Freise committed Feb 07, 2014 23 24  if value==None: return value  Daniel Brown committed Feb 25, 2014 25   Andreas Freise committed Dec 02, 2013 26 27 28 29 30 31  if type(value)==list: return [convertToFloat(s) for s in value] else: return convertToFloat(value) def convertToFloat(value):  32   Daniel Brown committed Feb 25, 2014 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48  try: # first just try and convert the value return float(value) except ValueError as ex: # Catch any casting exeception value = value.strip() # only the last value can be an SI scaling letter last = value[-1] if last in __suffix: # remove last character and append the SI scaling value = value[0:-1] + __suffix[last] else: raise pkex.BasePyKatException("Could not convert SI scaling in '{0}' to a float".format(value))  49   Daniel Brown committed Feb 25, 2014 50 51 52 53  try: return float(value) except ValueError as ex: raise pkex.BasePyKatException("Unable to convert '{0}' into a float".format(value))