# HG changeset patch # User Kim Alvefur # Date 1591282588 -7200 # Node ID c5f26f9adb31c1cd127237576249cb18d6824ed9 # Parent 5d113332855ce361002a6be43f01f31a2892eead util.human.units: Factor out function for getting multiplier diff -r 5d113332855c -r c5f26f9adb31 util/human/units.lua --- a/util/human/units.lua Thu Jun 04 16:54:52 2020 +0200 +++ b/util/human/units.lua Thu Jun 04 16:56:28 2020 +0200 @@ -46,17 +46,10 @@ "Yi", 2^80, } --- n: number, the number to format --- unit: string, the base unit --- b: optional enum 'b', thousands base -local function format(n, unit, b) --> string +local function adjusted_unit(n, b) local round = math_floor; local prefixes = large; local logbase = 1000; - local fmt = "%.3g %s%s"; - if n == 0 then - return fmt:format(n, "", unit); - end if b == 'b' then prefixes = binary; logbase = 1024; @@ -66,9 +59,22 @@ end local m = math_max(0, math_min(8, round(math_abs(math_log(math_abs(n), logbase))))); local prefix, multiplier = unpack(prefixes, m * 2-1, m*2); - return fmt:format(n / (multiplier or 1), prefix or "", unit); + return multiplier or 1, prefix; +end + +-- n: number, the number to format +-- unit: string, the base unit +-- b: optional enum 'b', thousands base +local function format(n, unit, b) --> string + local fmt = "%.3g %s%s"; + if n == 0 then + return fmt:format(n, "", unit); + end + local multiplier, prefix = adjusted_unit(n, b); + return fmt:format(n / multiplier, prefix or "", unit); end return { + adjust = adjusted_unit; format = format; };