Page 1 of 1

Convert distance to Percent with two decimal numbers

Posted: Saturday 02 May 2020 10:11
by besix
Hey
I have a simple script that converts the distance to a percentage but gives a percentage with a large decimal number. how to make only two decimal numbers

Code: Select all

local pct_sensor = 'OpaƂ'
local depth_sensor = 'Dystans'
local tank_height = 100

return {
        on = {
                devices = {depth_sensor}
        },
        execute = function(dz, device)
		local depthdev = dz.devices(depth_sensor)
		local pctdev = dz.devices(pct_sensor)
		local depth = depthdev.state
		
		-- Calculate percentage 
		local pct = (tank_height - depth) / tank_height * 100 
		dz.log('Tank update to ' .. pct.. '% ' , dz.LOG_INFO)
		pctdev.updatePercentage(pct)
	
end
}
		 
I get 40.349456%
I want 40.35%
Who will help ?

Re: Convert distance to Percent with two decimal numbers

Posted: Saturday 02 May 2020 10:13
by waaren
besix wrote: Saturday 02 May 2020 10:11 I have a simple script that converts the distance to a percentage but gives a percentage with a large decimal number. how to make only two decimal numbers

I get 40.349456%
I want 40.35%
Changing line

Code: Select all

		local pct = (tank_height - depth) / tank_height * 100 
to

Code: Select all

               local pct = dz.utils.round((tank_height - depth) / tank_height * 100 ,2)
should do it.

Re: Convert distance to Percent with two decimal numbers  [Solved]

Posted: Saturday 02 May 2020 20:37
by besix
It works now, Thank you very much! Waaren