Module:Radix: Difference between revisions
Jump to navigation
Jump to search
Created page with "local r = {} r.decimal_to = function(frame) -- Get arguments from call local decimal = abs(tonumber(frame.args[1])) local sign = decimal > 0 and "" or "-" -- If decimal is 1, return itself if decimal == 1 then return tostring(decimal) end -- Newradix is the radix to convert to local newradix = tonumber(frame.args[2]) local characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" -- precision is the number of digits below 1 to use -- if decimal is less than 1/new..." |
No edit summary |
||
| Line 3: | Line 3: | ||
r.decimal_to = function(frame) | r.decimal_to = function(frame) | ||
-- Get arguments from call | -- Get arguments from call | ||
local decimal = abs(tonumber(frame.args[1])) | local decimal = math.abs(tonumber(frame.args[1])) | ||
local sign = decimal > 0 and "" or "-" | local sign = decimal > 0 and "" or "-" | ||
-- If decimal is 1, return itself | -- If decimal is 1, return itself | ||
Revision as of 09:47, 4 July 2026
Documentation for this module may be created at Module:Radix/doc
local r = {}
r.decimal_to = function(frame)
-- Get arguments from call
local decimal = math.abs(tonumber(frame.args[1]))
local sign = decimal > 0 and "" or "-"
-- If decimal is 1, return itself
if decimal == 1 then
return tostring(decimal)
end
-- Newradix is the radix to convert to
local newradix = tonumber(frame.args[2])
local characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
-- precision is the number of digits below 1 to use
-- if decimal is less than 1/newradix ^ precision, return 0
local precision = tonumber(frame.args[3]) or 0
if decimal < newradix ^ (precision * -1) then
return "0"
end
-- final string to yeet everything into
local ret = sign
local maxpower = 1
local minpower = newradix ^ precision
if decimal > 0 then
-- Get highest power of newradix less than decimal
while maxpower < decimal do
maxpower = maxpower * newradix
end
maxpower = maxpower / newradix
-- Double loop
-- Outer loop: While maxpower >= minpower, add result of second loop to ret
-- Inner loop: While decimal >= maxpower, subtract maxpower from decimal
while maxpower > minpower do
local digit = 1
while decimal >= maxpower do
decimal = decimal - maxpower
digit = digit + 1
end
-- digit now contains number of maxpowers, concat it onto ret
ret = ret .. string.sub(characters, digit, digit)
maxpower = maxpower / newradix
end
return ret
else
-- Decimal is 0, also return itself
return tostring(decimal)
end
end
return r