Jump to content

Module:ConvertMaxWidth

From Shark's Hypothetical Weather
Revision as of 19:25, 3 January 2026 by Sharkius (talk | contribs)

Documentation for this module may be created at Module:ConvertMaxWidth/doc

local p = {}

-- Add comma separators
local function addCommas(n)
    local s = tostring(n)
    while true do
        s, k = s:gsub("^(-?%d+)(%d%d%d)", "%1,%2")
        if k == 0 then break end
    end
    return s
end

function p.main(frame)
    local args = frame.args

    -- Input value (yards)
    local yards = tonumber(args[1])
    if not yards then
        return "Error: Invalid or missing yard value."
    end

    local precision = tonumber(args['precision']) or 1
    local abbr = args['abbr'] or 'on'

    -- Conversions
    local miles = yards / 1760
    local km = yards * 0.0009144

    -- Formatting
    local formattedYards = addCommas(math.floor(yards))
    local formattedMiles = string.format("%." .. precision .. "f", miles)
    local formattedKm = string.format("%." .. precision .. "f", km)

    if abbr == 'on' then
        return formattedYards .. " [[wikipedia:Yard|yards]] (" ..
               formattedMiles .. " [[wikipedia:Mile|mi]]; " ..
               formattedKm .. " [[wikipedia:Kilometre|km]])"
    else
        return formattedYards .. " yards (" ..
               formattedMiles .. " miles; " ..
               formattedKm .. " kilometers)"
    end
end

return p