OH3 Rules DSL Calculation for kWh - UoM?

Hi All

I have the following rule which I am trying to use to calculate my Last Months electricity consumption:

rule "EM Mains Monthly Process"
    Item ShellyEM_MAINS_TotalEnergy_Switch changed to ON
    //Time cron "0 10 10 * *"
    var EMToDate = ShellyEM_MAINS_TotalEnergy.state as Number 
    logInfo("shelly_em", "EMToDate: " + EMToDate.toString())

    var PreviousMonth = ShellyEM_Mains_TotalEnergy_PreviousMonth.state as Number 
    logInfo("shelly_em", "PreviousMonth: " + PreviousMonth.toString())

    var UsageLastMonth = (EMToDate as Number - PreviousMonth as Number) 
    logInfo("shelly_em", "UsageLastMonth: " + UsageLastMonth.toString())


The log entries I see are:

09:28:59.745 [INFO ] [g.openhab.core.model.script.shelly_em] - EMToDate: 16653.434 kWh
09:28:59.745 [INFO ] [g.openhab.core.model.script.shelly_em] - PreviousMonth: 16648.39 kWh
09:28:59.745 [INFO ] [g.openhab.core.model.script.shelly_em] - UsageLastMonth: 18158400

So EMToDate and PreviousMonth are correct, however the calculated result UsageLastMonth is not.

I am currently not updating the Item so preserve my data as the calculation is not working.

I cannot work out what I have done incorrectly? Maybe something to do with UoM, but would appreciate any hints?
Items are configured as Number:Energy

Any help would be appreciated.

Found solution here.

It’s the “as Number” that caused your issue, by treating the Quantity Type values as plain Number values you lost the magic units-of-measurement handling capability.

More about this here, tips’n’tricks for Quantity types -