Convert String item to Number item in OH2

Hello all,

I have had a bit of trouble converting an output of the EXEC 2.0 (OH2) binding (which is always a “String” type) into a “Number” type, with many solutions being only valid for OH1.X it seems. So for anyone who wants a simple conversion, here is my ugly-but-works solution:

The output of the EXEC looks already like a Number, in this case it was e.g. 23.30.

Basically, I had to create another item of “Number” type and then write a rule that fires whenever the EXEC output changes. The rule then converts the output into a Float type. The “replace” part now replaces blanks if there are any. It could also be used to replace e.g. “°C” to nothing etc.

example.items:

String Pi_temp	   "Temperature [%s °C]"    {channel="exec:command:pitemp:output"}
Number Pi_temp_num "Temperature [%.1f °C]"

example.rules:

rule "Pi Temperature String to Number"
when
    Item Pi_temp changed
then
    Pi_temp_num.postUpdate(Float::parseFloat(String::format("%s",Pi_temp.state).replace(' ','')))
end

I am sure this solution is not the prettiest but - it works!
If you have a simpler or more direct way to convert this, let me know.

3 Likes

Thanks for posting this nice solution!

Two small remarks: The global variable is not needed. In fact the whole script should work after removing the first line. Instead of the last line you could also write (reasons discussed elsewhere in this forum):

Pi_temp_num.postUpdate(num1)

Thanks for the suggestion. I was able to make the rule a bit more sleek (first post updated)!

1 Like

Many thanks for your your example!

One small hint:

If you have the second Item as a KNX-item and would send it to your KNX-bus, you have to change postUpdate to sendCommand. Your rule should be like this:

rule "Pi Temperature String to Number"
when
    Item Pi_temp changed
then
    Pi_temp_num.sendCommand(Float::parseFloat(String::format("%s",Pi_temp.state).replace(' ','')))
end
2 Likes

It is really good advice for ever!
But could you write full rule and items?

I used it succesfully in my rules, thanks a lot!