aboutsummaryrefslogtreecommitdiffstats
path: root/util/human/units.lua
diff options
context:
space:
mode:
authorKim Alvefur <zash@zash.se>2020-06-04 16:56:28 +0200
committerKim Alvefur <zash@zash.se>2020-06-04 16:56:28 +0200
commit15b298c191115c9acdba05d9bd2cf8d3d64f0468 (patch)
treef674262d2c8ed4c296376061ae84352300e330ba /util/human/units.lua
parentf86aaa431f2135df07ea543060fb9457b5654639 (diff)
downloadprosody-15b298c191115c9acdba05d9bd2cf8d3d64f0468.tar.gz
prosody-15b298c191115c9acdba05d9bd2cf8d3d64f0468.zip
util.human.units: Factor out function for getting multiplier
Diffstat (limited to 'util/human/units.lua')
-rw-r--r--util/human/units.lua24
1 files changed, 15 insertions, 9 deletions
diff --git a/util/human/units.lua b/util/human/units.lua
index 5a083783..af233e98 100644
--- a/util/human/units.lua
+++ b/util/human/units.lua
@@ -46,17 +46,10 @@ local binary = {
"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 @@ local function format(n, unit, b) --> string
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;
};