Remove extra digits from a number

Hello! I am currently stuck at what I’m doing because I can’t think of a solution to my problem. Is it possible to make for example 35 to 30, 1029 to 1000, 1349249 to 1000000? Thanks!

Do you want to use it for number abbreviation? Like turn 298,253 into 298K?

yes, I actually do want to use abbreviation

Ok. I can help you with that. The instructions are not that complicated, but just do the steps correctly. Now here’s the code.

--put this in a module script
local AbbreviatedNumber = {}

local abbreviations = {
	K = 4,
	M = 7,
	B = 10,
	T = 13
}

function AbbreviatedNumber:Abbreviate(number)
	local text = tostring(math.floor(number))

	local chosenAbbreviation
	
	local function getLastCharFromString(str)
		return string.sub(str,string.len(str)) or false
	end
	
	for abbreviation, digits in pairs (abbreviations) do
		if #text >= digits and #text < (digits + 3)then
			chosenAbbreviation = abbreviation
			break
		end
	end

	if chosenAbbreviation then
		local digits = abbreviations[chosenAbbreviation]

		local rounded = math.floor(number / 10 ^ (digits - 2)) * 10 ^ (digits - 2)
		local pretext = string.format("%.1f",rounded / 10 ^ (digits - 1))
		if getLastCharFromString(pretext) == "0" then
			pretext = pretext:gsub(".?$","")
			pretext = pretext:gsub(".?$","")
		end
		text = pretext..chosenAbbreviation
	else
		text = number
	end
	return text
end

return AbbreviatedNumber

Put it into replicatedStorage and name it AbbreviateNumber
When you want to call it, you can do this:

local number = 348972394


local newNumber = require(game.ReplicatedStorage.AbbreviateNumber):AbbreviateNumber(number)
print(newNumber) -- this will print the new number
1 Like

Thank you so much, it worked perfectly!

Your welcome :slight_smile:

(Character limit)