How can I get the 3 first or last digit of a number?

I want to know how I can get the last or first 3 digit of a number, how can I achieve that ?

Also, if a number has leading zeros in the 3 last digit, how can I get a string that keep those leading zeros ?

The simplest way to do this is probably tostring(number), which converts other lua types into strings. You can then use the string library to read the first and/or last three digits like this:

local num = 120234521
num = tostring(num) -- convert number to a string
print(num:sub(1,3)) -- substring the first 3 digits
print(num:sub(#num-2)) -- substring last three digits.

If you dont want to include decimals, after converting the number to a string you can redefine the string as num:split(".")[1].
Hope this helps!

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.