Comparison

util/human/units.lua @ 10903:c5f26f9adb31

util.human.units: Factor out function for getting multiplier
author Kim Alvefur <zash@zash.se>
date Thu, 04 Jun 2020 16:56:28 +0200
parent 10890:a451f80d1cea
child 12573:0f4feaf9ca64
comparison
equal deleted inserted replaced
10902:5d113332855c 10903:c5f26f9adb31
44 "Ei", 2^60, 44 "Ei", 2^60,
45 "Zi", 2^70, 45 "Zi", 2^70,
46 "Yi", 2^80, 46 "Yi", 2^80,
47 } 47 }
48 48
49 -- n: number, the number to format 49 local function adjusted_unit(n, b)
50 -- unit: string, the base unit
51 -- b: optional enum 'b', thousands base
52 local function format(n, unit, b) --> string
53 local round = math_floor; 50 local round = math_floor;
54 local prefixes = large; 51 local prefixes = large;
55 local logbase = 1000; 52 local logbase = 1000;
56 local fmt = "%.3g %s%s";
57 if n == 0 then
58 return fmt:format(n, "", unit);
59 end
60 if b == 'b' then 53 if b == 'b' then
61 prefixes = binary; 54 prefixes = binary;
62 logbase = 1024; 55 logbase = 1024;
63 elseif n < 1 then 56 elseif n < 1 then
64 prefixes = small; 57 prefixes = small;
65 round = math_ceil; 58 round = math_ceil;
66 end 59 end
67 local m = math_max(0, math_min(8, round(math_abs(math_log(math_abs(n), logbase))))); 60 local m = math_max(0, math_min(8, round(math_abs(math_log(math_abs(n), logbase)))));
68 local prefix, multiplier = unpack(prefixes, m * 2-1, m*2); 61 local prefix, multiplier = unpack(prefixes, m * 2-1, m*2);
69 return fmt:format(n / (multiplier or 1), prefix or "", unit); 62 return multiplier or 1, prefix;
63 end
64
65 -- n: number, the number to format
66 -- unit: string, the base unit
67 -- b: optional enum 'b', thousands base
68 local function format(n, unit, b) --> string
69 local fmt = "%.3g %s%s";
70 if n == 0 then
71 return fmt:format(n, "", unit);
72 end
73 local multiplier, prefix = adjusted_unit(n, b);
74 return fmt:format(n / multiplier, prefix or "", unit);
70 end 75 end
71 76
72 return { 77 return {
78 adjust = adjusted_unit;
73 format = format; 79 format = format;
74 }; 80 };