Help Needed Abbreviating Numbers and Decimals

I am wanting to turn a number into an abbreviated number (example, 3.5K+), however, I’m not sure how I can find the second number (5). The second number is represented by second in the code below.

Here are examples of what I mean:
450,300 = 450.3K+
100,500,430,500 = 100.5B+
54,300,201 = 54.3M+

Here is the code:

function Math:Abbreviate(number)
	if number < 1000 then 
		return tostring(number)
	end

	local digits = math.floor(math.log10(number)) + 1
	local index = math.min(#Abbreviations, math.floor((digits - 1) / 3))
	local front = number / math.pow(10, index * 3)
	local second = --Help Here

	return string.format("%i.%d%s+", front, second, Abbreviations[index])
end

Any help is appreciated, thank you!

This is admittedly not the best way to do it, but it is one way.

function FormatNumber(num)
	if num > 1000000000000 then
		return tostring(math.floor(num /  100000000000) / 10).."T"
	elseif num > 1000000000 then
		return tostring(math.floor(num /  100000000) / 10).."B"
	elseif num > 1000000 then
		return tostring(math.floor(num /  100000) / 10).."M"
	elseif num > 1000 then
		return tostring(math.floor(num /  100) / 10).."K"
	else 
		return tostring(num)
	end
end

The extra / 10 will give you the decimal point that you desire. You can optimize this structure to use a dictionary with the suffix letters and corresponding number of digits i.e K, M, B, etc.

1 Like