From 4c0acd35552f213effcea1df275242f3a4476ae3 Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Thu, 3 Aug 2017 00:12:31 +0200 Subject: eng_str(): Adding unit argument. --- src/ee/formatting/__init__.py | 46 ++++++++++++++++++++++++++++++++----------- 1 file changed, 34 insertions(+), 12 deletions(-) (limited to 'src/ee/formatting') diff --git a/src/ee/formatting/__init__.py b/src/ee/formatting/__init__.py index a1e27a4..42bf48d 100644 --- a/src/ee/formatting/__init__.py +++ b/src/ee/formatting/__init__.py @@ -59,18 +59,40 @@ def e_series_find_closest(value): return min(series, key=lambda v: abs(v - value)) * 10**e -def eng_str(value): - big = ['', ' k', ' M', ' G', ' T'] - e_floor = math.floor(math.log10(value)) +import numpy +def eng_str(value, unit = None): - div3 = int(math.floor(e_floor/3)) - suffix = big[div3] - scale = 10**(div3*3) - scaled = value/scale - - if scaled == int(scaled): - return "{:1.0f}{}".format(scaled, suffix) + if value == 0: + s = '0' + (' ' + unit if unit is not None else '') else: - return "{:1.1f}{}".format(scaled, suffix) + big = ['k', 'M', 'G', 'T'] + small = ['m', 'u', 'p'] + + if unit is not None: + big = [' ' + unit] + [' ' + x + unit for x in big] + small = [' ' + unit] + [' ' + x + unit for x in small] + else: + big = [''] + [' ' + x for x in big] + small = [''] + [' ' + x for x in small] + + e_floor = math.floor(math.log10(value)) + + div3 = math.floor(e_floor/3) + if div3 > 0: + suffixes = big + idx = int(div3) + else: + suffixes = small + idx = int(-div3) + + suffix = suffixes[idx] + scale = 10**(div3*3) + scaled = value/scale + + if (scaled - math.floor(scaled)) < 0.0001: +# if scaled == math.floor(scaled): + s = "{:1.0f}{}".format(scaled, suffix) + else: + s = "{:1.1f}{}".format(scaled, suffix) -# return "scaled={:>9}, div3={}, floor(e)={}, scale={}, suffix={}".format(str(scaled), div3, e_floor, scale, suffix) + return s -- cgit v1.2.3