وحدة:NumberSpell

This module takes a number and returns the equivalent English word. For example, "2" becomes "two" and "79" becomes "seventy-nine". Numbers must be integers between 0 and 100.

Usage

{{#invoke:NumberSpell|main|number}}

Examples

  • {{#invoke:NumberSpell|main|8}} → ثمانية
  • {{#invoke:NumberSpell|main|56}} → ستة وخمسون
  • {{#invoke:NumberSpell|main|101}}Error: input must be an integer between 0 and 100

-- This module converts a number into its written English form.
-- For example, "2" becomes "two", and "79" becomes "seventy-nine".

local getArgs = require('Module:Arguments').getArgs

local p = {}

local max = 100 -- The maximum number that can be parsed.

local ones = {
	[0] = 'صفر',
	[1] = 'واحد',
	[2] = 'اثنين',
	[3] = 'ثلاثة',
	[4] = 'أربعة',
	[5] = 'خمسة',
	[6] = 'ستة',
	[7] = 'سبعة',
	[8] = 'ثمانية',
	[9] = 'تسعة'
}

local specials = {
	[10] = 'عشرة',
	[11] = 'احدى عشر',
	[12] = 'اثنا عشر',
	[13] = 'ثلاثة عشر',
	[15] = 'خمسة عشر',
	[18] = 'ثمانية عشر',
	[20] = 'عشرون',
	[30] = 'ثلاثون',
	[40] = 'أربعون',
	[50] = 'خمسون',
	[60] = 'ستون',
	[70] = 'سبعون',
	[80] = 'ثمانون',
	[90] = 'تسعون',
	[100] = 'مائة'
}

local formatRules = {
	{num = 90, rule = '%s وتسعون'},
	{num = 80, rule = '%s وثمانون'},
	{num = 70, rule = '%s وسبعون'},
	{num = 60, rule = '%s وستون'},
	{num = 50, rule = '%s وخمسون'},
	{num = 40, rule = '%s وأربعون'},
	{num = 30, rule = '%s وثلاثون'},
	{num = 20, rule = '%s وعشرون'},
	{num = 10, rule = '%s عشر'}
}

function p.main(frame)
	local args = getArgs(frame)
	local num = tonumber(args[1])
	local success, result = pcall(p._main, num)
	if success then
		return result
	else
		return string.format('<strong class="error">Error: %s</strong>', result) -- "result" is the error message.
	end
	return p._main(num)
end

function p._main(num)
	if type(num) ~= 'number' or math.floor(num) ~= num or num < 0 or num > max then
		error('input must be an integer between 0 and ' .. tostring(max), 2)
	end
	-- Check for numbers from 0 to 9.
	local onesVal = ones[num]
	if onesVal then
		return onesVal
	end
	-- Check for special numbers.
	local specialVal = specials[num]
	if specialVal then
		return specialVal
	end
	-- Construct the number from its format rule.
	onesVal = ones[num % 10]
	if not onesVal then
		error('Unexpected error parsing input ' .. tostring(num))
	end
	for i, t in ipairs(formatRules) do
		if num >= t.num then
			return string.format(t.rule, onesVal)
		end
	end
	error('No format rule found for input ' .. tostring(num))
end

return p