isteqsnip gaming
isteqsnip gaming

Reputation: 31

How can you turn a number like 1k into 1000 in lua?

I am currently working on a game in Roblox studio, and I'm wondering How can you turn a number like 1k into 1000 in lua?

Upvotes: 2

Views: 358

Answers (1)

Luke100000
Luke100000

Reputation: 1539

A quick solution would be a lookup table with all postfixes, for example something like this:

local postfixes = {
    ["n"] = 10^(-6),
    ["m"] = 10^(-3),
    ["k"] = 10^3,
    ["M"] = 10^6,
    ["G"] = 10^9,
}

local function convert(n)
    local postfix = n:sub(-1)
    if postfixes[postfix] then
        return tonumber(n:sub(1, -2)) * postfixes[postfix]
    elseif tonumber(n) then
        return tonumber(n)
    else
        error("invalid postfix")
    end
end

print(convert("1k"))
print(convert("23M"))
print(convert("7n"))
print(convert("7x"))
1000.0
23000000.0
7e-06
invalid postfix

Upvotes: 4

Related Questions