This piece of code
function shortennumber(locale, value, format, decimal_places, ignore_minimum_grouping_digit, currency, currency_digits)
decimal_places = type(decimal_places) == 'table' and decimal_places or { decimal_places or 0 };
local v_len = #tostring(value);
local r_format = format[v_len] or format[#format];
r_format = r_format.other or r_format;
if r_format == '' or r_format == '0' then
if currency then
return n.FormatCurrency(locale, value, currency, 'standard', currency_digits, true, ignore_minimum_grouping_digit);
else
return n.FormatDecimal(locale, value, true, ignore_minimum_grouping_digit);
end;
end;
local _, len = r_format:gsub('0', '0');
len = len + math.max(v_len - #format, 0);
local dp = decimal_places[len] or decimal_places[#decimal_places];
local r_value;
if type(value) == 'number' then
r_value = math.floor((value / (10 ^ math.max(v_len - len, 0))) * (10 ^ dp)) / (10 ^ dp);
else
r_value = (value / (BigInteger.new(10) ^ (v_len - len))):Floor(dp);
end;
r_format = (format[v_len] or format[#format])[locale.numbers.pluralForm(r_value)] or r_format;
r_format = (r_format:gsub('0+', ('0'):rep(math.max(v_len - #format, 0)) .. ',%1.' .. ('#'):rep(dp)));
return _parse(locale, r_format, r_value, true, ignore_minimum_grouping_digit, currency, false);
end;
It works but it could be faster, hereās what Iām not satsified with:
- This function relies on pattern string replacement for decimal places
- And slightly too much maths
Any better way to shorten number, and what could be improved?