Numbers are glitched

I made a function to convert numbers like 27284 to 27.2K or 5612080 to 5.61M but it sometime return a value with lots of 0 between the last number and the letter. How can I fix this? It’s very annoying.

function GetShortNumber(number)
	local textLenght = string.len(tostring(number))
	local textScale = math.floor((textLenght-1)/3)
	local reducedText = number/10^(textScale*3)
	local textRound = 10^(math.fmod(textLenght-1,3)-2)

	return tostring(math.floor(reducedText/textRound)*textRound)..quantity[textScale+1]
end
1 Like

This forum post looks to have a lot of useful info on how to do this:

2 Likes

Maybe: n = string.format(“%.2f”, value)
Just a number to string conversion. 1 or 2

1 Like

I tested the script in the tutorial but there still are the 0 spam glitch.
Do you know how to round numbers without getting this glitch?

I think I have a theory on how to solve your problem, but it would only work if the number inputted is a whole number

Edit: @Azerty_103 I asked the AI assistant to give it a go and create a number abbreviation function, and it made one that works quite well:

local function abbreviateNumber(number)
	local suffixes = {'', 'K', 'M', 'B', 'T', 'Q'}
	local suffixIndex = 1

	while number >= 1000 and suffixIndex < #suffixes do
		number = number / 1000
		suffixIndex = suffixIndex + 1
	end

	return string.format("%.2f%s", number, suffixes[suffixIndex])
end

It’s called a rounding error. Basically, since computers use binary system to count, it comes with a set of problems. In short - lua sucks at math.
The only way to fix this is either truncating the number or getting rid of the floating point (decimal part) by multipliying the number by let’s say 10^6 and then dividing the result by that same number.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.