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

Any (minor) help with a String Manipulation problem?

Asked by 8 years ago

I was working on a string formation, in terms of shorting money-based values, but I have come to a halt. The basic code below was a quick, rough draft that I created in my head (and it works), but it doesn't "fully" work.

The Code:

function ChangeValue(num)
if num > 999 then -- If num is 1000 or above
    num = math.floor(num/1000) ... "K"
elseif num > 999999 then -- if num is 1000000 or above
    num = math.floor(num/1000000) ... "M"
end
return num
end

-- EDIT: I CHANGED THE CODE A LITTLE BIT IN TERMS FOR THIS QUESTION.

So, My question is, how do I make this much more efficient and shorten the number based values via default, but also show how much is currently present. (I.e 1,200 --> 1.2K and 1,020 --> 1.02). I do know that I need to use Modulus and string manipulation, but I'm still unclear with that part of Lua at the current minute.

1 answer

Log in to vote
0
Answered by 8 years ago

Well I have a little function I wrote that does just that.

function Convert(num)
local x = tostring(num)
if #x>=13 then
local num1 = (#x-12)
return x:sub(0,(num1)).."."..(x:sub(#x-10,(#x-10))).."Q+" --Quadrillion
elseif #x>=10 then
 local num1 = (#x-9)
    return x:sub(0,(num1)).."."..(x:sub(#x-7,(#x-7))).."B+" --Billion
elseif #x>= 7 then
 local num1 = (#x-6)
return x:sub(0,(num1)).."."..(x:sub(#x-5,(#x-5))).."M+" --Million
elseif #x>=4 then
    return x:sub(0,(#x-3)).."."..(x:sub(#x-2,(#x-2))).."K+" --Thousand
else
return num
end
end

And you also don't need to use modules or anything for this, you just need a good understanding of algebra to create these kinds of functions.

Ad

Answer this question