Sari la conținut

Modul:Formatnum

De la Wikipedia, enciclopedia liberă
local p = {}


-- this function receives a number, tries to guess the layout and returns the 
-- same number with the thousand separator stripped and the decimal separator
-- converted to English format
p._stripSeparators = function(input)
	local comma = ','
	local dot = '%.'
	local _, commaCount = string.gsub(input, comma, comma)
	local _, dotCount = string.gsub(input, dot, dot)
	mw.logObject(commaCount, "Comma count")
	mw.logObject(dotCount, "Dot count")
	if dotCount == 0 then
		if commaCount == 0 then --plain old integer
			return tonumber(input)
		elseif commaCount == 1 then -- floating point, Romanian format
			--TODO better guesswork
			return tonumber(string.gsub(input, comma, dot), 10)
		else -- integer with thousand separator
			return tonumber(string.gsub(input, comma, ""), 10)
		end
	elseif dotCount == 1 then
		if commaCount == 0 then  --floating point, English format
			--TODO better guesswork
			return tonumber(input, 10)
		elseif commaCount == 1 then --one each; the last one is decimal sep
			local commaIndex = mw.ustring.find(input, comma)
			local dotIndex = mw.ustring.find(input, dot)
			if commaIndex > dotIndex then
				return tonumber(string.gsub(string.gsub(input, dot, ""), comma, dot), 10)
			else
				return tonumber(string.gsub(input, comma, ""), 10)
			end
		else -- float with thousand separator comma
			return tonumber(string.gsub(input, comma, ""), 10)
		end
	else
		if commaCount == 0 then  --integer with thousand separator
			return tonumber(string.gsub(input, dot, ""), 10)
		elseif commaCount == 1 then -- float with thousand separator dot
			return tonumber(string.gsub(string.gsub(input, dot, ""), comma, dot), 10)
		else -- invalid
			return nil
		end
	end
end

function p.stripSeparators(frame)
	mw.logObject(frame)
	return p._stripSeparators(frame.args[1])
end

return p