Jump to content

Module:Util

From RiskiPedia

Template:Documentation subpage

Description

This module provides a collection of common utility functions that can be reused by other Lua modules on the wiki.

format_with_commas

The `format_with_commas` function takes a number and returns it as a string formatted with commas as thousands separators. It will round any non-integer number to the nearest whole number before formatting.

Usage

From another Lua module (Recommended)

To use this function in another module, first load the module, then call the function:

-- Load the module at the top of your script
local Util = require('Module:Util')

-- Then call the function where needed
local myNumber = 1234567
local formattedNumber = Util.format_with_commas(myNumber) -- "1,234,567"

From wikitext

You can call this function directly from wikitext using {{#invoke:}}. This is useful for testing or simple one-off uses.

{{#invoke:Util|format_with_commas|NUMBER}}

Examples

Wikitext Result
{{#invoke:Util|format_with_commas|1234}} 1,234
{{#invoke:Util|format_with_commas|123456789}} 123,456,789
{{#invoke:Util|format_with_commas|1000}} 1,000
{{#invoke:Util|format_with_commas|999}} 999
{{#invoke:Util|format_with_commas|-45000}} -45,000
{{#invoke:Util|format_with_commas|12345.67}} (note rounding) 12,346

local p = {}

-- Format a number with commas as thousands separators
function p.format_with_commas(arg)
	local n -- This will hold the number to format
	
	if type(arg) == 'table' then
		-- If 'arg' is a table, we were called by #invoke
		-- The number is the first argument, e.g., {{#invoke:Util|format_with_commas|1234}}
		n = arg.args[1]
	else
		-- Otherwise, we were called by 'require()'
		-- 'arg' is the number itself
		n = arg
	end
	
	-- Make sure we're working with a number
	local num = tonumber(n)
	
	if not num then
		-- If input is invalid (e.g., "hello" or "nil"), just return it
		return tostring(n or "nil")
	end

	-- Round to the nearest whole number
	num = math.floor(num + 0.5) 
	
	local s = tostring(num)
	local sign, int = s:match("^([%-]?)(%d+)$")
	
	if not int then 
		return s -- Not a number we can format
	end
	
	-- Add commas
	int = int:reverse():gsub("(%d%d%d)", "%1,")
	int = int:reverse():gsub("^,", "")
	
	return sign .. int
end

return p