Module:MathUtil

local util_args = require('Module:ArgsUtil') local util_map = require('Module:MapUtil') local util_text = require('Module:TextUtil') -- MathUtil local p = {}

function p.sign(v) if v == 0 then return 0 end return (v > 0 and 1) or -1 end

function p.printWithSign(v) return (v > 0 and ('+%s'):format(v)) or v end

function p.roundnum(v, bracket) bracket = bracket or 1 return math.floor(v/bracket + p.sign(v) * 0.5) * bracket end

function p.percent(v, bracket) return p.roundnum(v * 100, bracket or 2) .. '%' end

function p.mod(a, b)	return a - math.floor(a/b)*b end

function p.sum(tbl) local total = 0 for _, v in pairs(tbl) do		total = total + v	end return total end

function p.tonumber(str) if not str then return nil end local raw_number = str:gsub(',','') return tonumber(raw_number) end

function p.formatNumber(str) local num = tonumber(str) if num then return mw.getLanguage('en'):formatNum(num) else return str end end

function p.serializeNumber(N) local chr = tostring(N):sub(-1) local lookup = { ['1'] = 'st', ['2'] = 'nd', ['3'] = 'rd' } return N .. (lookup[chr] or 'th') end

function p.deserialize(str) local deserialized = str:gsub('[A-Za-z]*','') if deserialized == '' then return nil end return deserialized end

function p.deserializeRangeToTable(str) str = str:gsub('[A-Za-z]*','') return util_map.split(str, '%-', tonumber) end

function p.padleft(num, digits) local str = tostring(num) local tbl = util_text.split(str, '') local len = #tbl local outputTbl = {} for k = 1, len do		outputTbl[k] = tbl[len + 1 - k]	end for k = len + 1, digits do		outputTbl[k] = '0' end local outputReversed = table.concat(outputTbl, '') return outputReversed:reverse end

return p