rounding floats

Posted on
Mon Jan 23, 2017 11:20 am
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

rounding floats

This is likely for Matt and or Jay..
Updating states with
dev.updateStateOnServer(stateName,round(value,1))
where value is a float

And sometimes get
Screen Shot 2017-01-23 at 11.09.25.png
Screen Shot 2017-01-23 at 11.09.25.png (6.16 KiB) Viewed 1521 times
instead of 9.2

I know that float to string sometimes is not exact(*), but how can I avoid getting 10 digits. This is just the opposite of what should happen

Karl


(*) from docs.pytho.org
Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

Posted on
Mon Jan 23, 2017 4:27 pm
matt (support) offline
Site Admin
User avatar
Posts: 21411
Joined: Jan 27, 2003
Location: Texas

Re: rounding floats

Instead of using round() try using the optional decimalPlaces argument:

Code: Select all
dev.updateStateOnServer(stateName, value, decimalPlaces=1)

Image

Posted on
Mon Jan 23, 2017 5:46 pm
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

Re: rounding floats

i actually use updateStatesOnServer(changeList) which has a mix of several things strings, int, floats
changeList =[{"key":key1,"value":value},{...},{..}]

if I add decimal places for strings/int is that ignored? ... and how would I specify that parameters in list changeList

Thanks for the quick reply
Karl

Posted on
Mon Jan 23, 2017 8:57 pm
matt (support) offline
Site Admin
User avatar
Posts: 21411
Joined: Jan 27, 2003
Location: Texas

Re: rounding floats

I don't recall if it is ignored for those types (probably so), but "decimalPlaces" is actually one of the keys you can specify in the changeList dict your pass in. Thus, you can specify it only for your state values that are floats.

Image

Posted on
Mon Jan 23, 2017 9:58 pm
kw123 offline
User avatar
Posts: 8333
Joined: May 12, 2013
Location: Dallas, TX

Re: rounding floats

yes that works, adds a little bit more complexity to the update (check if decimalPlaces !="") ..

thanks, looks much nice now


Karl

Page 1 of 1

Who is online

Users browsing this forum: No registered users and 4 guests