Module:BaseConvert
Revision as of 09:38, 22 February 2013 by blackwiki>Toohool (←Created page with '-- -- Converts numbers to a specified base between 2 and 36, for use in -- templates such as {{binary}}, {{octal}}, {{hexadecimal}}, etc. -- local p = {} funct...')
Converts numbers to a specified base between 2 and 36, for use in templates such as {{binary}}, {{octal}}, {{hexadecimal}}, etc.
Example usage:
local BaseConvert = require('Module:BaseConvert')
BaseConvert.convert({n = 14600926, base = 16}) -- returns 'DECADE'
Arguments:
- n - (required) the number to be converted, as a string. It may be a number instead, if the input base is 10.
- base - (required) the base to which the number should be converted. May be between 2 and 36, inclusive.
- from - the base of the input. Defaults to 10 (or 16 if the input has a leading '0x'). Note that bases other than 10 are not supported if the input has a fractional part.
- precision - number of digits to be rendered after the radix point. Trailing zeros will be added if needed. If not specified, however many digits are needed will be shown, up to 10.
- width - minimum number of digits to be rendered before the radix point. Leading zeros will be added if needed.
- default - Value to return if n is empty or non-numeric. Defaults to the value of n.
- prefix / suffix - wikitext to add before/after the returned result. Will not be added if n is empty or non-numeric. For example, you might use a prefix of
0xwhen converting to hex, or a suffix of<sub>8</sub>when converting to octal.
--
-- Converts numbers to a specified base between 2 and 36, for use in
-- templates such as {{binary}}, {{octal}}, {{hexadecimal}}, etc.
--
local p = {}
function p._convert(n, base)
local digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
n = math.floor(n)
local sign = ''
if n < 0 then
sign = '-'
n = -n
end
local t = {}
repeat
local d = (n % base) + 1
n = math.floor(n / base)
table.insert(t, 1, digits:sub(d, d))
until n == 0
return sign .. table.concat(t, '')
end
function p.convert(frame)
local n = frame.args.n
local base = frame.args.base
return p._convert(n, base)
end
return p