Enhance round function in dzVents/runtime/Utils.lua
Posted: Thursday 30 July 2020 12:49
Hello folks,
I just converted half of my lua scripts to dzVents scripts.
In the domoticz.utils.round I mis the option to use negative decimals as a way to round on the left side of the indented point.
-1 should round 3333.333 to 3330
-2 should round 3333.333 to 3300
-3 should round 3333.333 to 3000
etcetera
My testresults:
2020-07-30 12:30:00.613 Status: dzVents: Info: Test 333.333 dz.utils.round sGroep2_WattRnd=333
2020-07-30 12:30:00.613 Status: dzVents: Info: Test 333.333 dz.utils.fRound sGroep2_WattRnd=300
2020-07-30 12:30:00.613 Status: dzVents: Info: Debug script_time: Rounding number: 333.333 with idp -2 for Groep2_Watt
Current code:
Suggested code enhancement:
I just converted half of my lua scripts to dzVents scripts.
In the domoticz.utils.round I mis the option to use negative decimals as a way to round on the left side of the indented point.
-1 should round 3333.333 to 3330
-2 should round 3333.333 to 3300
-3 should round 3333.333 to 3000
etcetera
My testresults:
2020-07-30 12:30:00.613 Status: dzVents: Info: Test 333.333 dz.utils.round sGroep2_WattRnd=333
2020-07-30 12:30:00.613 Status: dzVents: Info: Test 333.333 dz.utils.fRound sGroep2_WattRnd=300
2020-07-30 12:30:00.613 Status: dzVents: Info: Debug script_time: Rounding number: 333.333 with idp -2 for Groep2_Watt
Current code:
Code: Select all
function self.round(value, decimals)
local nVal = tonumber(value)
local nDec = ( decimals == nil and 0 ) or tonumber(decimals)
if nVal >= 0 and nDec > 0 then
return math.floor( (nVal * 10 ^ nDec) + 0.5) / (10 ^ nDec)
elseif nVal >=0 then
return math.floor(nVal + 0.5)
elseif nDec and nDec > 0 then
return math.ceil ( (nVal * 10 ^ nDec) - 0.5) / (10 ^ nDec)
else
return math.ceil(nVal - 0.5)
end
end
Code: Select all
function self.round(value, idp)
local nVal=tonumber(value)
local idp=tonumber(idp)
local mult = 10^(idp or 0) --Round number to identent point
if nVal >= 0 then
roundednum=math.floor(nVal * mult + 0.5) / mult
else
roundednum=math.ceil(nVal * mult - 0.5) / mult
end
local str = tostring(roundednum)
if str:sub(-2) == ".0" then str=str:sub(1,-3) end
return tonumber(str)
end