Suffix number causes round up issue

I have a function that suffixs large numbers to be shortend, however it’s round up, causing incorrect info the be told to the player

function SuffixNumber(number)
	if number == 0 then
		return 0
	end

	local Suffixes =
		{ "K", "M", "B", "T", "Qa", "Qi", "Sx", "Sp", "Oc", "No", "Dc", "Ud", "Dd", "Td", "Qad", "Qu", "Sd", "St" }

	local i = math.floor(math.log(number, 1e3))
	local v = math.pow(10, i * 3)

	return string.gsub(string.format("%.1f", number / v), "%.?00+$", "") .. (Suffixes[i] or ""), Suffixes
end
print(SuffixNumber(9999)) -- prints 10.0k

9999 should display as 9.99k, no 10.0k

1 Like

I think for starters you’ll need to change the .1f to at least .2f. I’m not 100% sure what your gsub pattern is all about, I’m guessing for getting rid of trailing zeroes? If so you may even want to use .3f in you format string

1 Like

Work with the number then format it into a string.

1 Like

Hello!

A way I found working was by firstly formatting %.1f relative to i and saving the returned string into a variable like this:

local formatNumber = string.format("%."..(3 * i).."f", number / v)

And then remove the last digits (relative with i too) with string.sub() like this:

return formatNumber:sub(1, #formatNumber - (3 * i - 2)) .. Suffixes[i], Suffixes

However, to stop “normal” numbers to break the system, one can replace:

if number == 0 then
     return 0
end

with:

if number < 1000 then
     return number
end

So the function looks like this:

function SuffixNumber(number)
	if number < 1000 then
		return number  -- return all numbers that don't need a suffix instantly
	end

	local Suffixes =
		{ "K", "M", "B", "T", "Qa", "Qi", "Sx", "Sp", "Oc", "No", "Dc", "Ud", "Dd", "Td", "Qad", "Qu", "Sd", "St" }

	local i = math.floor(math.log(number, 1e3))
	local v = 10 ^ (i * 3)  -- a "synonym" of math.pow

	local formatNumber = string.format("%."..(3 * i).."f", number / v)  -- format the number relative to i
	return formatNumber:sub(1, #formatNumber - (3 * i - 2)) .. Suffixes[i], Suffixes  -- get the length of the string, cut the last digits and return it
end

There is probably an easier way of doing this, however, this is a way based on the code beforehand.

Hope I could help!

How can I get it to cut off unneccessary numbers tho? 10000 returns 10.00K, I just want 10K

Ah, that’s much easier! Just do this inside your function, where you return your value:

return tostring(math.floor(number / v)) .. Suffixes[i], Suffixes

Hope that solves it!

That then removes all decimals. 9999 should show 9.99K, 10000 should show 10K. With that return, 9999 shows just 9K