Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can you deal with large numbers?

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?

2 comments

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.

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.

2 answers

✓ Accepted answer

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

2 comments

0

is Instance.new not Instance.New

0

intvalue.Changed:Connect(scoreboardCalculations()) is running the function not passing the function to the Changed event

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.

1 comment

0

^

This discussion is preserved as it was. New answers, comments, and votes are closed.