Module:number base: Difference between revisions
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 | local floor,insert = math.floor, table.insert | ||
n = floor( | function basen(n,b) | ||
local digits = " | 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 % | local d = (n % b) + 1 | ||
n = floor(n / | 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