Module:number base: Difference between revisions

From Linguifex
Jump to navigation Jump to search
No edit summary
No edit summary
 
Line 4: Line 4:


-- Ross Berteig on SO: https://stackoverflow.com/a/3554821
-- Ross Berteig on SO: https://stackoverflow.com/a/3554821
function export.base12(n)
local floor,insert = math.floor, table.insert
     n = floor(tonumber(n))
function basen(n,b)
     local digits = "0123456789AB"
     n = floor(n)
    if not b or b == 10 then return tostring(n) end
     local digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
     local t = {}
     local t = {}
    local sign = ""
    if n < 0 then
        sign = "-"
    n = -n
    end
     repeat
     repeat
         local d = (n % 12) + 1
         local d = (n % b) + 1
         n = floor(n / 12)
         n = floor(n / b)
         insert(t, 1, digits:sub(d,d))
         insert(t, 1, digits:sub(d,d))
     until n == 0
     until n == 0
     return table.concat(t)
     return sign .. table.concat(t)
end
 
function export.base12(n)
return basen(n,12)
end
end


return export
return export

Latest revision as of 16:53, 13 June 2025

Documentation for this module may be created at Module:number base/doc

local export = {}

local floor, insert = math.floor, table.insert

-- Ross Berteig on SO: https://stackoverflow.com/a/3554821
local floor,insert = math.floor, table.insert
function basen(n,b)
    n = floor(n)
    if not b or b == 10 then return tostring(n) end
    local digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    local t = {}
    local sign = ""
    if n < 0 then
        sign = "-"
    n = -n
    end
    repeat
        local d = (n % b) + 1
        n = floor(n / b)
        insert(t, 1, digits:sub(d,d))
    until n == 0
    return sign .. table.concat(t)
end

function export.base12(n)
	return basen(n,12)
end

return export