Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to check if string is an integer?

Asked by
NorteX_tv 101
6 years ago

I have a TextBox and I need to check if the player has input integer (no letters or special symbols) Something like: if (string.isInteger) == true/false

0
You can find all numbers using %d+ pattern EpicMetatableMoment 1444 — 6y
0
Or you can replace all non numbers with gsub and the pattern %D+ EpicMetatableMoment 1444 — 6y
0
The `tonumber(...)` function returns nil if conversion fails -> `if tonumber(string) ~= nil then` fredfishy 833 — 6y
0
`~= nil`'s redundany as the if statement will check if a value's true or not. TheeDeathCaster 2368 — 6y

3 answers

Log in to vote
0
Answered by
6z3cho 0
4 years ago
Edited 4 years ago
local isaint = tonumber(script.Parent.Text)

if isaint then
    -- valid number

else
    --invalid number
end
0
this is a really good method, especially in vanilla lua but requires it to be converted first to a string which is a bit ucky when we could round the number and compare :) JedDevs 20 — 3y
Ad
Log in to vote
0
Answered by
Ciyob86 25
4 years ago
function isInt(var)
    if type(var) = "int" then
        return true
    else
        return false
    end
end
0
This sadly won't work as one roblox doesn't acknowledge shorthand and second they don't have number types, only 'number' which could be a float or integer. JedDevs 20 — 3y
Log in to vote
0
Answered by
JedDevs 20
3 years ago

The simplest and most performant solution is to attempt to round the number then compare, if it's an integer it'll be equivelant.

local function isInteger(num)
    if math.floor(num) == num then
        return true
    end
    return false
end

Answer this question