Documentation for this module may be created at Module:Round/doc
-- for comparing numbers but leaving trailing zeros so sorts are cleaner
local p = {}
function p.main(frame)
local args = frame:getParent().args
local n = args[1]
n = string.gsub(n,',','')
n = tonumber(n,10)
if not n then
return 'Value is not a number'
end
local round = args.round or args[2]
-- I don't think commas matter; we're not going to allow more than 10 probably
round = tonumber(round,10)
if not round then
return 'Rounding is not a number'
end
return p.round(n,round)
end
-- rounds a number and then adds trailing zeros
-- only after the decimal point
-- negative rounding implies numbers before the decimal point are removed
-- but that can be done with #expr
-- this is meant for padding, which #expr can't do
function p.round(n,r)
n = tonumber(n,10)
r = tonumber(r,10)
if not (n and r) then
return '--'
end
r = math.floor(r)
if r < 1 then
return math.floor(n)
end
-- get decimal parts
n = tostring(n)
n = mw.text.split(n,'%.')
local int,dec = n[1],n[2]
if not dec then
dec = 0
end
-- round the decimal part
dec = '0.' .. dec
dec = tonumber(dec,10)
local rexp = 10 ^ r
dec = math.floor(dec * rexp + 0.5) / rexp
dec = tostring(dec) .. string.rep('0',r)
-- cut down to desired round
-- start at 3 because of "0.x"
dec = string.sub(dec,3,2+r)
-- recombine
n = string.format('%s.%s',int,dec)
return n
end
return p