Module:Number

Revision as of 21:34, 12 March 2024 by Ricewind (talk | contribs) (Add general numbers function for handling numerical values)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

--
-- Module that contains functions related to numeric formatting or number manipulation
--

local p = {}

--[[
    Parses a string representation of a number with suffixes (k, m, b, t, q, s, o, n, d).

    Parameters:
        str (string): The string to parse.

    Returns:
        number: The numeric value represented by the input string or 0 if the string is NaN.
]]
function p.parseNumber(str)
	local suffixes = {
        k = 1e3,
        m = 1e6,
        b = 1e9,
        t = 1e12,
        q = 1e15,
        s = 1e18,
        o = 1e21,
        n = 1e24,
        d = 1e30
    }

	-- Empty/nil string.
	if not str or str == "" then
        return 0
    end
    
    local suffix = str:sub(-1):lower()
    local multiplier = suffixes[suffix] or 1
    local number = tonumber(str)

    if not number then
        return 0
    end

    return number * multiplier
end