Anonymous

Module:Number: Difference between revisions

From Melvor Idle
no edit summary
m (Add uniform docs)
No edit summary
Line 36: Line 36:
end
end
end     
end     
--- Rounds a number to a specified number of digits after the decimal point.
-- @param val (number or string) The value to round.
-- @param maxDigits (number) [optional] The maximum number of digits after the decimal point.
-- @param minDigits (number) [optional] The minimum number of digits after the decimal point.
-- @return (string) The rounded number with the specified number of digits after the decimal point, or the input unchanged if it's not a number.
function p.round(val, maxDigits, minDigits)
if val == nil then
return nil
else
if type(maxDigits) == "table" then
minDigits = maxDigits[2]
maxDigits = maxDigits[1]
end
local result = val..""
local decimals = string.find(result, "%.")
if decimals ~= nil then
decimals = string.len(result) - decimals
else
decimals = 0
end
if maxDigits ~= nil and decimals > maxDigits then
result = string.format("%."..maxDigits.."f", result)
elseif minDigits ~= nil and decimals < minDigits then
result = string.format("%."..minDigits.."f", result)
end
return result
end
end
--- Rounds a number to a specified number of decimal places.
-- @param num (number) The number to round.
-- @param numDecimalPlaces (number) [optional] The number of decimal places to round to.
-- @return (number) The rounded number with the specified number of decimal places, or the nearest integer if numDecimalPlaces is not provided.
--From http://lua-users.org/wiki/SimpleRound
function p.round2(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
return math.floor(num * mult + 0.5) / mult
end
-- Euclidean Greatest Common Divisor algorithm
function p.gcd(a, b)
if b ~= 0 then
return p.gcd(b, a % b)
else
return math.abs(a)
end
end
--Formats a pair of numbers as a reduced fraction
function p.fraction(n, d)
local gcd = p.gcd(n, d)
return p.formatnum(n/gcd)..'/'..p.formatnum(d/gcd)
end
--Similar to p.fraction but returns the simplified numerator and denomerator separately without formatting
function p.fractionpair(n, d)
local gcd = p.gcd(n, d)
return n / gcd, d / gcd
end
--Returns a number including the sign, even if positive
function p.numStrWithSign(number)
if number >= 0 then
return '+'..p.formatnum(number)
else
return p.formatnum(number)
end
end


--- Clamps a value between a minimum and maximum range.
--- Clamps a value between a minimum and maximum range.
2,875

edits