Module:Decimals

From Universalis
Jump to navigation Jump to search

Documentation for this module may be created at Module:Decimals/doc

require('Module:No globals')

local p = {}

function p._main(n, d)
	local num = tonumber(n)
	if not num then
		error('Unable to convert "' .. tostring(n) .. '" to a number')
	end
	local decimals = tonumber(d)
	if not decimals then
		error('Unable to convert "' .. tostring(d) .. '" to a number')
	end
	local maxDecimals = 14 - math.floor(math.log10(num)) -- to allow a maximum of 15 significant figures, which is the highest guaranteed correct with doubles
	if decimals > maxDecimals then decimals = maxDecimals end
	local mult = 10^decimals
	num = math.floor(num * mult + 0.5) / mult
	if decimals < 0 then
		return tostring(num)
	else
		return string.format('%.' .. decimals .. 'f', num)
	end
end

function p.main(frame)
	local args, pargs = frame.args, frame:getParent().args
	return p._main(pargs[1], pargs[2])
end

return p