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

[Solved] How to best divide large numbers (>1,000) for leaderboard/GUI?

I'm wanting to display numbers in shorthand, like 137B instead of putting 137,000,000,000 on the leaderboard. However, after 1e+23 (or 10^23), my function starts returning 9s in place of where 1s, 10s, and 100s should be. This is my current code:

_G.abbreviateLNum = function(n)
	local orgN = n
	local tableNum = 0
	local x = 3
	if n >= 1000 then
		while n >= 1000 do
			print(n)
			n = math.floor(orgN/math.pow(10,x))
			tableNum = tableNum + 1
			x = x + 3
		end
		return n..NumberSuffixes[tableNum].."+"
	else
		return n
	end
end

Thanks in advance for any suggestions/answers.

2 comments

0

Your code does work, but accomplishes the very same thing this script accomplishes. It also starts returning 9s at the same point. Thank you, though.

2 answers

✓ Accepted answer

This is more of a string problem than a math problem. Here, I put together something that should produce the result you're expecting.

local function abbrevNum(num)
	local suffixes = {"K", "M", "B", "T"}
	local zeros = #tostring(math.floor(num)) - 1

	local suffix_num = math.floor(zeros/3)
	local abbrev = suffixes[suffix_num]
	local base = math.pow(1000, suffix_num)

	if abbrev then
		local quant = string.match(num/base, "%d+%.?%d?")
		if num > base*quant then abbrev = abbrev .. "+" end
		return quant .. abbrev
	end

	return num
end

print(abbrevNum(1234)) --> 1.2k+
print(abbrevNum(12345)) --> 12.3k+
...
print(abbrevNum(3498238)) --> 3.4M+

We're basically just getting what power of 1000 we need by using floor(zeros/3) as the index to the list of suffixes, then getting the place value of the number by raising 1000 to that power. This is the base = math.pow(1000, suffix_num) portion.

If the abbreviation is in the list, then this is where the string manipulation comes in. We're essentially just turning the number into scientific notation then cropping out the following decimal place.

Hope this helped. Let me know if you have any questions.

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