-- Copyright (C) 2018 CurlyMo & Niek -- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. local M = {} local function round(num, numDecimalPlaces) local mult = 10^(numDecimalPlaces or 0) return math.floor(num * mult + 0.5) / mult end function M.run(a, b, c) if a == nil or b == nil or c ~= nil then error("FORMAT requires two arguments"); end if tonumber(a) ~= nil then error(string.format("FORMAT argument #1 expected string, \"%s\" given", type(a))); end if tonumber(b) == nil then error(string.format("FORMAT argument #2 expected number, \"%s\" given", type(b))); end local stringparts = pilight.common.explode(a, "%"); if #stringparts == 0 then -- nothing to format return a; end local sresult = ""; for i = 1 , #stringparts, 1 do local thispart = stringparts[i]; if string.sub(thispart, 1 , 1) == "i" or string.sub(thispart, 1 , 1) == "f" then local j = 2; local srest = ""; local snum = ""; local inum = 0; while tonumber(string.sub(thispart, j , j)) ~= nil do -- get number following %i or %f snum = snum .. string.sub(thispart, j, j); j = j + 1; end if string.len(snum) > 0 then inum = tonumber(snum); end srest = string.sub(thispart, j); -- round so fraction will fit local numstring = tostring(round(b, snum)); local numparts = pilight.common.explode(numstring, "."); local intpart = "0"; local fractpart = "0"; if numparts[1] ~= nil then intpart = numparts[1] end if numparts[2] ~= nil then fractpart = numparts[2] end if string.find(thispart, "i") == 1 then if string.len(intpart) < inum then sresult = sresult .. string.rep("0", inum - string.len(intpart)) .. intpart .. srest; else sresult = sresult .. intpart .. srest; end else if string.len(fractpart) < inum then sresult = sresult .. string.rep("0", inum - string.len(fractpart)) .. fractpart .. srest; else sresult = sresult .. fractpart .. srest; end end else if i > 1 then sresult = sresult .. "%"; end sresult = sresult .. thispart; end end return sresult; end function M.info() return { name = "FORMAT", version = "1.0", reqversion = "8.1.1", reqcommit = "0" } end return M;