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

How can you deal with large numbers?

Asked by 5 years ago

Hello, i have the following issue.

my game allows player to get a very large score having 10 digits in the leader board looks ridicules so i came up with the following solution

    if n > 1000 then
        return math.floor(n / 1000) .. "K"
    elseif n > 1000000 then
        return math.floor(n / 1000000) .. "M"
    else
        return n .. ""
    end

the issue is where should i place the statement?

should i make it into a function then call it every time a script changes to score value? or is there a way to run something everytime a value is changed?

0
You can make a NumberValue (an actual physical object) that contains the player's score and use the the Changed event on that. I don't really use dataStore or leaderboards much so I couldn't tell you exacty where to store the NumberValue, that's up to you. Trew86 175 — 5y
0
Slightly off topic but you need to check for n > 1000000 first instead of n > 1000 because if the score is 100000000 for example it still uses K instead of M. Rheines 661 — 5y

2 answers

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

If you store the number in a IntValue object then you can create a listener for when the IntValues value changes

local intvalue = Instance.new("IntValue")

scoreboardCalculations = function()

    if n > 1000 then
        return math.floor(n / 1000) .. "K"
    elseif n > 1000000 then
        return math.floor(n / 1000000) .. "M"
    else
        return n .. ""
    end

end

intvalue.Changed:Connect(scoreboardCalculations)

The code might need a little cleaning up i'm working off a crappy tablet Hope this helped

0
is Instance.new not Instance.New yHasteeD 1819 — 5y
0
intvalue.Changed:Connect(scoreboardCalculations()) is running the function not passing the function to the Changed event User#5423 17 — 5y
Ad
Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

You can convert the value to string then use the length of the string to get the correct unit.

Example

local unitTable = {"K","M"} -- unit list

local function formatNumber(val)
    -- count the string length take 1 to give us the base 3 count
    -- math.floor is the same as v - (v % 1)
    local unit = math.floor((#tostring(val) - 1) / 3)

    if unitTable[unit] then
        -- return a string with the correct using using ^ for devision
        return tostring(math.floor( val / (1000 ^ unit))) .. unitTable[unit]
    end

    return tostring(val) 
end

for i=0, 1000000, 100 do
    print(formatNumber(i))
end

Hope this helps.

0
^ ScriptGuider 5640 — 5y

Answer this question