From f255d99215e34cc02c9b6aa5375a984fb862538f Mon Sep 17 00:00:00 2001 From: Jag <77469789+jag3dagster@users.noreply.github.com> Date: Tue, 25 Jun 2024 23:06:31 -0700 Subject: [PATCH] feat(math): add math.round function (#603) --- imports/math/shared.lua | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/imports/math/shared.lua b/imports/math/shared.lua index b1f3de9c..bdc38a5b 100644 --- a/imports/math/shared.lua +++ b/imports/math/shared.lua @@ -197,4 +197,25 @@ function math.lerp(start, finish, duration) end end +---Rounds a number to a whole number or to the specified number of decimal places. +---@param value number | string +---@param places? number | string +---@return number +function math.round(value, places) + if type(value) == 'string' then value = tonumber(value) end + if type(value) ~= 'number' then error('Value must be a number') end + + if places then + if type(places) == 'string' then places = tonumber(places) end + if type(places) ~= 'number' then error('Places must be a number') end + + if places > 0 then + local mult = 10 ^ (places or 0) + return math.floor(value * mult + 0.5) / mult + end + end + + return math.floor(value + 0.5) +end + return lib.math