How to get -123 instead of 123?

i get an item with a number in it. But this number is positive, i want to have it negative.

How can i do this?

I have a rule file, which extracts the value from a string.

val solarpowerStr = solar_lines.get(4).split('#').get(1)

I tested the following, but with no luck, i got many errors:

Test 1:
val solarpowerStr1 = solarpowerStr * -1

Test 2:
stromzaehler1_leistung1.postUpdate(solarpowerStr * -1)

Can someone help me?

stromzaehler1_leistung1.postUpdate( “-” + solarpowerStr )

1 Like

That works, thank you!

Why is my rule not working? How can i do some math? Is this not the right notation, if i want to calculate a value?

Your variable starts out as string, can’t do maths on that. You’d need to type cast it as a number to work with it.

My suggestion was to add a string “-” to the front of yours - the result is still a string, but if your stromzaehler1_leistung1 is a Number Item, the postUpdate will do an automatic conversion)

Can you tell me how I can change the string to a number within the rule so that I can do math with it?

This works:

var hausverbrauch_aktuell = (Double::parseDouble(consumptionStr)) + (Double::parseDouble(solarpowerStr))

But i have another question:

When i declare my variable in my rule before the first “if”

for example:

var Number Test

Can i store a string in it and it will automatically be parsed to a number like i do with the following code? And what´s the difference between var and val?


Also i got some errors inside my rule. When i store a value to a variable inside a “if”, then i can´t use it after the “if”.

How can i use the variable after the “if”?


rule "example"
     when xxx
     val Test = 0
     if xxx {
          val Test = 1

Now i get item_1 = 1 and item_2 = 0.

What do i have to do, so that i can change a variable inside an “if” and use the variable with the new value outside the “if” too?

This might help

If you want to change Test, use var not val. Unless you want to create a new version of Test, don’t use var or val again. If you want Test to be consistent both inside and outside a {} block, use var or val to declare it outside the block.

Thank you for the link. So i think i always can use var, because the variables are changed through the rule and not set before.

If i declare:

var number Test

And after that i put a string in it, will this be parsed to a number or will the variable change to a string? When i put a string to a number-item, it will get parsed to a number, but what about variables???

And if i declare a variable once at the beginning of a rule, i can use the name of the variable later without “var” before the name?

Like this:

var test = 1
test = 2 + 5
test = 3 + 5

And not this way:

var test = 1
var test = 2 + 5
var test = 3 + 5

It’s very easy to try these things out