Rework functions in util.py
This commit is contained in:
32
util.py
32
util.py
@@ -1,4 +1,4 @@
|
||||
def shorten(val, prec=4, lowest=0, highest=0):
|
||||
def formatAmount(val, prec=4, lowest=0, highest=0):
|
||||
"""
|
||||
Add suffix to value, transform value to match new suffix and round it.
|
||||
|
||||
@@ -7,17 +7,32 @@ def shorten(val, prec=4, lowest=0, highest=0):
|
||||
prec -- precision of final number (number of significant positions to show)
|
||||
lowest -- lowest order for suffixizing
|
||||
highest -- highest order for suffixizing
|
||||
"""
|
||||
# Separate value to mantissa and suffix
|
||||
mantissa, suffix = suffixizeAmount(val, lowest, highest)
|
||||
# Round mantissa and add suffix
|
||||
newMantissa = processAmount(mantissa, prec)
|
||||
result = u"{0}{1}".format(newMantissa, suffix)
|
||||
return result
|
||||
|
||||
def suffixizeAmount(val, lowest, highest):
|
||||
"""
|
||||
Add suffix to value and transform value to match new suffix.
|
||||
|
||||
Keyword arguments:
|
||||
val -- value to process
|
||||
lowest -- lowest order for suffixizing
|
||||
highest -- highest order for suffixizing
|
||||
|
||||
Suffixes below lowest and above highest orders won't be used.
|
||||
"""
|
||||
# Take numbers only matching/above lowest possible positive suffix
|
||||
if abs(val) >= 1000 and highest >= 3:
|
||||
suffixmap = {3 : "k", 6 : "M", 9 : "G"}
|
||||
# Start from highest possible suffix
|
||||
for key in sorted(suffixmap, reverse = True):
|
||||
# Find first suitable suffix and check if it's not above highest order
|
||||
if val >= 10**key and key <= highest:
|
||||
return u"{0}{1}".format(process(val/float(10**key), prec), suffixmap[key])
|
||||
return val/float(10**key), suffixmap[key]
|
||||
# Take numbers between 0 and 1, and matching/below highest possible negative suffix
|
||||
elif abs(val) < 1 and val != 0 and lowest <= -3:
|
||||
suffixmap = {-6 : u'\u03bc', -3 : "m"}
|
||||
@@ -26,16 +41,15 @@ def shorten(val, prec=4, lowest=0, highest=0):
|
||||
# Check if mantissa with next suffix is in range [1, 1000)
|
||||
# Here we assume that each next order is greater than previous by 3
|
||||
if val < 10**(key+3) and key >= lowest:
|
||||
return u"{0}{1}".format(process(val/float(10**key), prec), suffixmap[key])
|
||||
# No suitable suffixes are found withing given order borders, or value
|
||||
return val/float(10**key), suffixmap[key]
|
||||
# If no suitable suffixes are found within given order borders, or value
|
||||
# is already within [1, 1000) boundaries, just return rounded value with no suffix
|
||||
else:
|
||||
return u"{0}".format(process(val, prec))
|
||||
return val, ""
|
||||
|
||||
|
||||
def process(val, prec):
|
||||
def processAmount(val, prec):
|
||||
"""
|
||||
Round number.
|
||||
Round number and return as string.
|
||||
|
||||
Keyword arguments:
|
||||
val -- value to round
|
||||
|
||||
Reference in New Issue
Block a user