Jump to content

Module:ConvertMaxWidth: Difference between revisions

From Shark's Hypothetical Weather
No edit summary
No edit summary
Line 10: Line 10:
end
end


local function round(n, decimals)
local function roundSigFig(num, sigfig)
     local m = 10 ^ decimals
    if num == 0 then return 0 end
     return math.floor(n * m + 0.5) / m
     local scale = 10 ^ (sigfig - math.floor(math.log10(math.abs(num))) - 1)
     return math.floor(num * scale + 0.5) / scale
end
end


Line 23: Line 24:
     end
     end


    -- Default to 3 significant figures (matches Wikipedia)
    local sigfig = tonumber(args['sigfig']) or 3
     local abbr = args['abbr'] or 'on'
     local abbr = args['abbr'] or 'on'


     -- Conversions
     -- Conversions (exact)
     local miles = yards / 1760
     local miles = yards / 1760
     local km = yards * 0.0009144
     local km = yards * 0.0009144


     -- Wikipedia-style rounding
     -- Sig-fig rounding
    local milesR = roundSigFig(miles, sigfig)
    local kmR = roundSigFig(km, sigfig)
 
     local formattedYards = addCommas(math.floor(yards))
     local formattedYards = addCommas(math.floor(yards))
     local formattedMiles = string.format("%.1f", round(miles, 1))
     local formattedMiles = tostring(milesR)
     local formattedKm = string.format("%.1f", round(km, 1))
     local formattedKm = tostring(kmR)


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

Revision as of 19:29, 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 roundSigFig(num, sigfig)
    if num == 0 then return 0 end
    local scale = 10 ^ (sigfig - math.floor(math.log10(math.abs(num))) - 1)
    return math.floor(num * scale + 0.5) / scale
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

    -- Default to 3 significant figures (matches Wikipedia)
    local sigfig = tonumber(args['sigfig']) or 3
    local abbr = args['abbr'] or 'on'

    -- Conversions (exact)
    local miles = yards / 1760
    local km = yards * 0.0009144

    -- Sig-fig rounding
    local milesR = roundSigFig(miles, sigfig)
    local kmR = roundSigFig(km, sigfig)

    local formattedYards = addCommas(math.floor(yards))
    local formattedMiles = tostring(milesR)
    local formattedKm = tostring(kmR)

    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