How to get first digit of an integer?

So, I need to check if a number (let’s say 101) is smaller than another number (let’s say 205) just because the first digit is smaller. The only thing that matters is the first digit.

I can do the rest but I’m stuck with the first problem, narrowing the integer to 1 digit

If you are directly comparing numbers you could just do 101 < 205, one method to find if a number is less than another number purely based on the first digit is you could do tonumber(string.sub(tostring(555), 1, 1))). This turns the number into a string and finds the first character of the string and turns that into a number.

1 Like

The above solution is a good universal solution that works for both (positive) integers and decimal numbers. The added benefit is that it’s a one-liner.

Here’s another solution that also gets the first digit of a (positive) integer that is ~10x faster than the current solution (doesn’t use expensive string/number calls):

local function GetFirstDigit(Integer)
	while Integer >= 10 do
		Integer = Integer / 10
	end
	return Integer
end

Of course, speed shouldn’t be a problem at all thanks to Luau.

3 Likes