Module:NumberAbbr: Difference between revisions
Appearance
MisterChuChu (talk | contribs) Increase max decimal places |
MisterChuChu (talk | contribs) Fix for inputs like "1.23456e11" resulting in "1.234B" instead of "123.456B" |
||
Line 2: | Line 2: | ||
function p.abbr(frame) | function p.abbr(frame) | ||
local f=frame | local f=frame | ||
local n= | local n=f.args[1]~=nil and tostring(f.args[1]) or "0" --number to abbreviate | ||
local dec=f.args[2]~=nil and math.min(math.max(f.args[2],0),11) or 3 --decimal places | local dec=f.args[2]~=nil and math.min(math.max(f.args[2],0),11) or 3 --decimal places | ||
local s=f.args[3]~=nil and math.max(f.args[3],3) or 6 --start at 10^ | local s=f.args[3]~=nil and math.max(f.args[3],3) or 6 --start at 10^ | ||
local abt=f.args[4]==nil and false or f.args[4] --use abbr tag? | local abt=f.args[4]==nil and false or f.args[4] --use abbr tag? | ||
if string.match(f.args[1],"[^0-9e%.%-%+]+")~=nil then --cancel abbreviation if no digits are found | |||
return f.args[1] | |||
else | else | ||
local n2="" --create additional variables | |||
local nn="" | |||
local ep=0 | |||
local isinf=false | |||
local nb=n --keep unmodified number if needed | |||
local m=string.sub(n,1,1)=="-" and 1 or 0 --check if negative | |||
n=string.sub(n,m+1,#n) --if so, remove minus at start | |||
if string.sub( | if string.sub(n,1,1)=="i" then --check if infinite | ||
nn=math.huge | nn=math.huge | ||
isinf=true | isinf=true | ||
else | else | ||
for nc in string.gmatch(n,"[0-9e%.%-%+]+") do --extract valid numerical characters | |||
nn=nn..nc | |||
end | |||
n2=nn --keep full number for later | |||
if | ep=string.find(nn,"e")~=nil and tonumber(string.sub(nn,string.find(nn,"e")+1,#nn)) or #nn>100 and #nn or math.floor(math.log10(nn)) --get exponent | ||
if string.sub(ep,1,1)=="i" then --check if exponent is infinite | |||
nn=math.huge | |||
isinf=true | |||
else | |||
nn=string.find(nn,"e")~=nil and string.sub(nn,1,string.find(nn,"e")-1) or nn --remove the exponent from number variable | |||
local nd=nn | |||
nn="" | |||
for nc in string.gmatch(nd,"[0-9]+") do --remove decimal point | |||
nn=nn..nc | |||
end | |||
if ep>=3 then --pad variable to 14 characters | |||
if #nn>14 then | |||
nn=string.sub(nn,1,14) | |||
else | |||
for i=#nn,13 do | |||
nn=nn.."0" | |||
end | |||
end | end | ||
end | end | ||
nn=tonumber(nn)>999 and tonumber(nn)/10^(13-ep%3) or nn | |||
nn=math.floor(nn*10^dec)/10^dec --remove unnecessary decimal places | |||
end | end | ||
end | end | ||
return (math.log10(n2)>=3 and ep>=s) and (abt and "<abbr title=\""..n.."\">" or "")..(m>0 and "-" or "")..nn..""..(not isinf and p.illion({args={math.floor(ep/3-1)}}) or "")..(abt and "</abbr>" or "") or nb | |||
end | end | ||
end | end | ||