Rounding Number Based on Significant Figures

If I have a number and want to round it either up or down according to significant figures how would I go about doing so?

Example: I want to round a series of numbers to two sig figs.
1: 56,218,489 → 56,000,000
2: 7,380 → 7,400
3: 918,247,543 → 92,000,000

Any help or a push in the right direction would be gratefully appreciated!

You could use the %.[n]g or %.[n]e specifier in string.format but it does convert them to scientific notation for some values (you should be able to convert them into decimal form using string manipulation).

Here’s an implementation that handles signed integers.

local function RoundToSignificantFigures(Number, SignificantFigures)
	Number = math.round(Number) --Integer coercion.
	local Divisor = if Number < 0 then string.len(Number) - SignificantFigures - 1 else string.len(Number) - SignificantFigures
	return math.round(Number / math.pow(10, Divisor)) * math.pow(10, Divisor)
end

local Values = {56218489, 7380, 918247543}
for _, Value in ipairs(Values) do
	print(RoundToSignificantFigures(Value, 2))
end

image

2 Likes