Module:number base

From Linguifex
Jump to navigation Jump to search

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