Add an optional decimalPlaces parameter to math.round()

As a Roblox developer, I would like math.round() to support rounding to a specific number of decimal places.

Currently, math.round() only rounds to the nearest integer. If I want to round a number to a fixed amount of decimal places, I need to write a helper such as:

local function Round(Number, DecimalPlaces)
	return tonumber(string.format("%." .. DecimalPlaces .. "f", Number))
end

or use a power-of-ten helper manually:

local function Round(Number, DecimalPlaces)
	local Scale = 10 ^ DecimalPlaces
	return math.round(Number * Scale) / Scale
end

I would like Roblox to support this directly:

local Rounded = math.round(12.34567, 2)
print(Rounded) -- 12.35

Proposed signature:

math.round(x: number, decimalPlaces: number?): number

Requested behavior:

  • Preserve current behavior when decimalPlaces is omitted.
  • If decimalPlaces is provided, round to that many decimal places.
  • Require decimalPlaces to be a non-negative integer.
  • Reject invalid values such as negative numbers, non-integers, math.huge, or NaN.

This would remove a very common helper function from projects and make numerical rounding clearer. string.format() is still useful when a developer needs display formatting with trailing zeroes, but math.round(x, decimalPlaces) would be better when the result should remain a number.

4 Likes

That would be too much, reserving a fast call and also its Luau part and not the Roblox API part now.
You can already do that by multiplying the value by something like 100 and then dividing it by 100 back after rounding.
Also use of helper functions always leads to runtime bloat…