Abbreviate Numbers with one line of code!

Dude, please make your own topic or flag it.

That’s why I wrote in one line… No one wants to understand so I can’t really do anything.

You did it some things wrong. Lemme rectify.

local number = 100000

local short = {"", "K", "M", "B", "T"} -- Add more

local function abbrievateNum()
local str = tostring(math.floor(number))
local substr = string.sub(str, 1, ((#str+2)%3) + 1)
local abbrievation = short[tonumber(((#str-1)/3)) +1]
print(substr..abbrievation)
return substr..abbrievation
end

workspace.Baseplate.Touched:Connect(abbreviateNum)

Now it’s growing an error:
attempt to concatenate string with nil

I was actually kind of force for the sake of readibility, but if I apply my real code, it would be way more faster. The recent code I wrote is for the sake of readibility, I forgot to state but you need to use the original code for it to be faster.

Uhh…I can rectify this by tomorrow because I’ll open my pc tom.

Sorry, but your original code errors. String manipulation will always be slower than maths though.

local short = {"", "K", "M", "B", "T"} -- Add more

local function abbrievateNum(number)
local str = tostring(math.floor(number))
return string.sub(str, 1, ((#str+2)%3) + 1)..short[tonumber(((#str-1)/3)) +1]
end

print(abbrievateNum(10))
Error:5: attempt to concatenate string with nil
stack backtrace:
5 function abbrievateNum

Yep, sorry, I’ll rectify it by tom, I haven’t actually tested it.

Okay, it’s something that happens, just make sure next time you do this test it before posting

2 Likes

Ok, so it’s actually a weird thing, the code itself is good, it does concatenate, but as you chose the number 10, it’s maybe in decimals, so I need to make it whole number. If you choose numbers greater than 3 digits, it works perfectly, I’ll convert decimal into a number

1 Like

Thanks! Sorry for answering so late, also do you have any updates?

1 Like

Yes, I actually fixed up everything and everything works perfectly!

1 Like