Module:PercentageCalculator

From The Walkscape Walkthrough

Percentage calculator does one thing, and one thing only (for now). It takes in a fraction and calculates a percentage. That percentage is returned as a string with 2 digits after the decimal.


Functions can be invoked by calling them like the following:

{{#invoke:PercentageCalculator|main|1/2}}

In this example, the call is made to this Module, followed by the function named 'main', followed finally by the parameter 1/2.

p.main(frame)

Inputs

frame A fraction in the form: X/Y

Outputs

string A decimal in the form: xx.xx%



local p = {}

function p.main(frame)
    local fraction = frame.args[1]
    local parts = mw.text.split(fraction, '/')
    local numerator = tonumber(parts[1])
    local denominator = tonumber(parts[2])

    if denominator == 0 then
        return '0%'
    else
        local percentage = (numerator / denominator) * 100
        return string.format("%.2f%%", percentage)
    end
end

return p