This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
blipman17's profile picture

Getting First or Last Digit

Started by blipman17, 03 June 2013 - 05:56 AM
blipman17 #1
Posted 03 June 2013 - 07:56 AM
Does anyone know a way of returning the first or last digit from a number? And after that deleting that number so i could repeat the first one and get a new number? I need it for an interdimentional data transferring system that rely's on wireless transmitters. I would be so happy.
Lyqyd #2
Posted 03 June 2013 - 01:28 PM
Split into new topic.

If you don't mind turning it into a string first, string.sub can get you the first or last character pretty easily.
SeventhGrave #3
Posted 03 June 2013 - 02:22 PM
If you don't want to use strings…


local lastdigit = number % 10
Would get you the last digit.


local firstdigit = math.abs(number)
while firstdigit >= 10 do
  firstdigit = math.floor(firstdigit/10)
end
Would get you the first digit.

I apologize if any of the syntax is incorrect, as I am still learning LUA. Feel free to correct it.
EDIT: My apologies, I guess I didn't think of decimal numbers. That being said, my lastdigit and firstdigit methods will not work for that situation.
Edited on 04 June 2013 - 10:38 AM
remiX #4
Posted 03 June 2013 - 02:28 PM
I'd go with Lyqyd's approach as I think it's the easiest to understand.
Engineer #5
Posted 03 June 2013 - 05:39 PM
To extend on remiX and Lyqyd:

So, like mentioned before, you can turn this number into a string. We can use the function tostring( ) for that. Then we can get the first or last character using string.sub. And after that, you can tonumber that string, to make it a string again.

So, the following is what you are looking for: (if you dont understand a function, google: lua <function>)

local digits = 774829
local function getLast( var )
     return tonumber( tostring(var):sub( -1 )
end

local function getFirst( var )
    return tonumber( tostring(var):sub( 1, 1) )
end

print( getLast(digits) )
print( getFirst(digits) )
H4X0RZ #6
Posted 03 June 2013 - 05:43 PM
Example:

local num = "12345" --the number

--Now here comes the first digit
local firstDigit = string.sub(num, 1,1) -- 1

--And the last number
local lastDigit = string.sub(num, #num,#num) -- 5


--And to delete the first number do this
local num = string.sub(num, 2, #num)

--To delete the last digit
local num = string.sub(num, 1, #num-1)
Cruor #7
Posted 03 June 2013 - 06:00 PM

i = 1234
while i ~= 0 do
    lastDigit = i % 10
    i = math.floor(i / 10)

    print(lastDigit)
end

As I am a much larger fan of dealing with numbers as numbers
Lyqyd #8
Posted 03 June 2013 - 06:33 PM
What if your number is 1234.56?