Lompat ke isi

Modul:MathExtra

Dari Wikipedia bahasa Indonesia, ensiklopedia bebas

local p = {}

local math_module = require( "Module:Math" )

--[[
	Calculate percent of a sum of numbers.
	
	This is mostly usefull when you have two numbers from parameters.
	1 = women count
	2 = men count
	=> percet of women / men + women (returns int)
]] 
function p.percentInt(frame)
	local a = tonumber(frame.args[1])
	local b = tonumber(frame.args[2])
	return percent(a, b, 0)
end

--[[
	Calculate percent of a sum of numbers.
	
	Same as percentInt, but returns float.
	For rounding precision use [3=] or [precision=] (default = 1)
]] 
function p.percent(frame)
	local a = tonumber(frame.args[1])
	local b = tonumber(frame.args[2])
	local precision = tonumber(frame.args[3] or frame.args.precision or 1)
	return percent(a, b, precision)
end

function percent(a, b, precision)
	local ab=a+b
	if (ab~=0) then
		return math_module._round( 100 * a / ab , precision )
	else
		return math_module._round(0, precision )
	end
end

--[[
--Tests:
print( "50", percent(1, 1) )
print( "25", percent(1, 3) )
--]]

return p