I already have a abbreviation system and it works, but it goes all funky at 100T. Can someone tell me what is going on? Here is my script(I have it in a module script and reference to it in other scripts): (Also, number is the value i'm working with)
local abbreviatednumber = {} local abb = { k = 4, M = 7, B = 10, T = 13, Qa = 16, Qn = 19, Si = 22, Sp = 25 } function abbreviatednumber:abb(number) local text = tostring(math.floor(number)) local chosenabb for abbreviations, digits in pairs(abb) do if #text >= digits and #text < (digits + 3) then chosenabb = abbreviations break end end if chosenabb then local digits = abb[chosenabb] local rounded = math.floor(number / 10 ^ (digits - 2)) * 10 ^ (digits - 2) text = string.format("%.1f", rounded / 10 ^ (digits - 1))..chosenabb else text = number end return text end return abbreviatednumber
tostring
displays very large numbers in a shortened way, such as 100 trillion as 10e+14. So when using tostring and # to get the 'length' of the number, it gets the text length of the shortened version instead.
Another way to find it, which wouldn't break for large numbers, is to use math.log10
. Short summary of log10
(base 10 logarithm):
if
y = 10^p
, thenp = math.log10(y)
So math.log10(1)
gives 0
, math.log10(10)
gives 1
, math.log10(100)
gives 2 and so on. math.log10(500)
will be between 2
and 3
, as 500
is between 100
and 1000
. Knowing this, one replacement for #tostring(math.floor(number))
is
math.floor(math.log10(number)) + 1
However log10
doesn't accept 0
, so you should make a special case if the input is 0
(like returning "0"). If support for negative numbers is needed (as log10
doesn't support them), math.abs(number)
can be passed to the math.log10
instead of number
.