How do you get a specific digit of a number?

Lets say I have a number 375, that number is (obviously) 3 digits long. How would I get a specific digit in that number?

Like, if I wanted to get digit 2, digit 2 would be 7, but what kind of algorithm could I use to get that digit :upside_down_face: ?

2 Likes

Fairly easy since strings and numbers are so easily changed in Lua.

string.sub(tostring(375), 2, 2)

375 probably doesn’t need to be inside of a tostring, but I am unsure and it is safer anyways.
2 and 2 need to be the same number.

4 Likes

A mathematical way of doing this is to divide the remainder of the number with 10^n by 10^n-1

function getDigit(num, digit)
	local n = 10 ^ digit
	local n1 = 10 ^ (digit - 1)
	return math.floor((num % n) / n1)
end

print(getDigit(375, 3)) -- 3
print(getDigit(375, 2)) -- 7
print(getDigit(375, 1)) -- 5
6 Likes

@Blokav

What if I wanted to get how many digits a number has? I assume it would be something like this: string.len(tostring(number))?

2 Likes

Spot on. When using strings, you can also use the # shortcut.

#tostring(375) --> 3

3 Likes

Yup. You can also do:

math.ceil(math.log10(num))

However, this only works on integers that are equal to or greater than 1.

1 Like