Jump to content

Module:ja-numeral

From Wiktionary, the free dictionary

See Template:ja-numeral for usage and examples.


local export = {}

local exponentarr = {
	{ num=10, numeral="十", ichiprefix=false },
	{ num=100, numeral="百", ichiprefix=false },
	{ num=1000, numeral="千", ichiprefix=false },
	{ num=10000, numeral="万", ichiprefix=true },
	{ num=100000000, numeral="億", ichiprefix=true },
	{ num=1000000000000, numeral="兆", ichiprefix=true },
	{ num=10000000000000000, numeral="京", ichiprefix=true },
	{ num=100000000000000000000, numeral="垓", ichiprefix=true }
}

local numarr = { "一", "二", "三", "四", "五", "六", "七", "八", "九" }

function export.convert(num)
	if num == nil then
		error("Nil")
	end
	
	num = tonumber(num)
	if num == nil then
		error("Nil")
	end
	
	if num == 0 then
		return "零"
	end
	if num == math.huge or num == (1 - math.huge) then
		error("Infinity not supported")
	end
	if num ~= num then
		error("NaN not supported")
	end
	if num ~= math.floor(num) then
		error("Decimals not supported")
	end
	if num < 0 then
		error("Negative number not supported")
	end
	
	local function convertrecursive(numeral, val)
		if val == 0 then
			return numeral
		end
		if val < 10 then
			return numeral .. numarr[val]
		end
		
		local biggestexponent = exponentarr[table.getn(exponentarr)]
		for i, exponent in ipairs(exponentarr) do
			if val < exponent.num then
				biggestexponent = exponentarr[i - 1]
				break
			end
		end
	
		local multiple = math.floor(val / biggestexponent.num)
		local multiplenumeral = numarr[multiple]
		if multiplenumeral == nil then
			return convertrecursive("", multiple)
				.. biggestexponent.numeral
				.. convertrecursive(numeral,
					val - biggestexponent.num * multiple)
		elseif multiple == 1 and not biggestexponent.ichiprefix then
			return convertrecursive(
				numeral .. biggestexponent.numeral,
				val - biggestexponent.num * multiple)
		else
			return convertrecursive(
				numeral .. multiplenumeral .. biggestexponent.numeral,
				val - biggestexponent.num * multiple)
		end
	end
	
	return convertrecursive("", num)
end

function export.show(frame)
	local params = { [1] = { required=true, type="number" } }
	local args = require("Module:parameters").process(frame.args, params)
	return export.convert(args[1])
end

return export