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
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.