Jump to content

Module:ConvertMaxWidth: Difference between revisions

From Shark's Hypothetical Weather
No edit summary
No edit summary
Line 1: Line 1:
local p = {}
local p = {}


-- Add comma separators
local function addCommas(n)
local function addCommas(n)
     local s = tostring(n)
     local s = tostring(n)
Line 9: Line 8:
     end
     end
     return s
     return s
end
local function round(n, decimals)
    local m = 10 ^ decimals
    return math.floor(n * m + 0.5) / m
end
end


Line 14: Line 18:
     local args = frame.args
     local args = frame.args


    -- Input value (yards)
     local yards = tonumber(args[1])
     local yards = tonumber(args[1])
     if not yards then
     if not yards then
Line 20: Line 23:
     end
     end


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


Line 27: Line 29:
     local km = yards * 0.0009144
     local km = yards * 0.0009144


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


     if abbr == 'on' then
     if abbr == 'on' then

Revision as of 19:27, 3 January 2026

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