Jump to content

Module:ConvertMaxWidth

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

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

local p = {}

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

local function round(n, decimals)
    local m = 10 ^ decimals
    return math.floor(n * m + 0.5) / m
end

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

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

    local abbr = args['abbr'] or 'on'

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

    -- Wikipedia-style rounding
    local formattedYards = addCommas(math.floor(yards))
    local formattedMiles = string.format("%.1f", round(miles, 1))
    local formattedKm = string.format("%.1f", round(km, 1))

    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