Module:Ordinal

-- don't delete this comment; -- it prevents accidental categorization of this module

local m = {};

-- tests if this value is considered inexistent local function isempty(x) return not x or x == ""; end

-- formats a number to an ordinal - as a numeral word up to numeral_max (excluding numeral_max), -- as digit + ordinal marker else -- maximum supported value for numeral_max: 100 function m.formatordinal(n, numeral_max) numeral_max = math.min(numeral_max or -1, 100); local unit = n % 10; local tens = (n % 100 - unit)/10; local rest = n - tens*10 - unit; local s = ""; -- main number if n < numeral_max then -- numeral words local unitnumerals = { [0] = "zero", "fir", "seco", "thi", "four", "fif", "six", "seven", "eigh", "nin", "ten", "eleven", "twelf", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; local tensnumerals = { "ten", "twent", "thirt", "fort", "fift", "sixt", "sevent", "eight", "ninet" }; if tens < 2 then s = unitnumerals[tens*10+unit]; elseif unit == 0 then s = tensnumerals[tens] .. "ie"; else s = tensnumerals[tens] .. "y-" .. unitnumerals[unit]; end else s = tostring(n); end -- determine suffix local suffix; if tens == 1 or unit == 0 or unit > 3 then suffix = "th"; elseif unit == 1 then suffix = "st"; elseif unit == 2 then suffix = "nd"; else suffix = "rd"; end -- compose ordinal return s .. suffix; end

-- computes an ordinal number function m.ordinal(f) -- validate input number local n = f.args[1]; if isempty(n) then return "Error: No number given"; end n = tonumber(n); if not n or n % 1 ~= 0 or n < 0 then return "Error: Invalid number given"; end -- check if we should use digits or numerals -- we do not support numerals for numbers > 99 local usenumerals = f.args["numeral"]; usenumerals = (not isempty(usenumerals)) and usenumerals ~= "no"; local numerals_max = -1; if usenumerals then numerals_max = tonumber(f.args["max numeral"]) or (n+1); end return m.formatordinal(n, numerals_max); end

return m; -- don't delete this comment (see comment at the top) --categories of this module follow here: