Converting a number to units tens hundreds and same for decimals

I want to be able to convert a number like 13.2 to its separate numbers like {10,3,0.2}. I have looked around and I don’t know if its just that I can’t word it properly but I can’t find how to do it anywhere. Thanks if you can help!

You can use this function:

local function splitNumber(num)
	local numStr = tostring(num)

	local parts = numStr:split(".")

	local integerPart = tonumber(parts[1])
	local tens = math.floor(integerPart / 10) * 10
	local units = integerPart % 10

	local decimals = tonumber("0." .. (parts[2] or "0"))

	return {tens, units, decimals}
end

-- Example usage
local number = 13.2
local components = splitNumber(number)
print(components[1], components[2], components[3])  -- Output: 10 3 0.2
function ConvertNumber(num)
    local whole = math.floor(num)
    local fractional = num - whole
    local ones = math.floor(whole)
    local tenths = math.floor(fractional * 10)
    local hundredths = math.floor((fractional * 10 - tenths) * 10)

    return {ones, tenths, hundredths}
end

-- Example usage
local number = 13.2
local components = ConvertNumber(number)
print(components) -- Output: {13, 2, 0}

This can be used regardless of how many powers of ten you need to separate.

--!strict
local function separatePowersOfTen(n: number, numberOfDecimals: number): {number}
	local maxExponent: number = math.floor(math.log10(n))
	local separatedPowersOfTen: {number} = table.create(maxExponent + numberOfDecimals + 1)
	for exponent: number = maxExponent, -numberOfDecimals, -1 do
		-- separatedPowerOfTen is (approximately) d * 10^exponent where d is a digit (0-9).
		local separatedPowerOfTen: number = n % 10^(exponent + 1) - n % 10^exponent
		separatedPowersOfTen[maxExponent - exponent + 1] = separatedPowerOfTen
	end
	return separatedPowersOfTen
end

local testNumber: number = 1234.56789
local testDecimals: number = 3
local separatedPowersOfTen: {number} = separatePowersOfTen(testNumber, testDecimals)
for i: number, separatedPowerOfTen: number in separatedPowersOfTen do
	local exponent: number = -testDecimals + #separatedPowersOfTen - i
	local formatString: string = if exponent >= 0 then "%i" else `%.{-exponent}f`
	print(string.format(formatString, separatedPowerOfTen))
end

These all work but ill leave the one I’m going to use as solution. Thanks for the help!

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