I’m reviving this old thread just so this Rounding issue’s solutions might be in one place.
I am doing energy monitoring and the math is creating numbers like 249.363648099999973338954077917151153087615966796875. I want to send myself an email each morning with the use for yesterday, but obviously it is sending this super long number and I would like to round it. I have tried almost all the options I could find online and they all generate an error, usually about type mismatch. I have tried your string option now as well, but get this error:
2016-08-15 08:37:00.009 [ERROR] [.o.m.r.i.engine.ExecuteRuleJob] - Error during the execution of rule Send usage email
java.util.IllegalFormatConversionException: f != org.openhab.core.library.types.DecimalType
Here is my rule with my email address hidden of course. You’ll see I commented out some of the previous tries:
rule "Send usage email"
when
Time cron "0 * * * * ?"
then
val energyMail = String::format("Energy use is %.1f", Energy_UseDaily.state as DecimalType)
// var energyMail = Energy_UseDaily.float as DecimalType
// var tmp = (Math::round(energyMail*10.0)/10.0)
sendMail("myemail", "Daily energy use", "Yesterday we used " + energyMail)
end
My Energy_UseDaily item looks like this:
Number Energy_UseDaily "Today's use [%.3f kW]" <calculator> (Energy)
rule "Send usage email"
when
Time cron "0 * * * * ?"
then
val energyMail = String::format("Energy use was %.1f kWh. ", (Energy_UseDaily.state as DecimalType).floatValue)
val energyUnits = String::format("There are %.1f units left.", (Energy_Meter.state as DecimalType).floatValue)
sendMail("myemail", "Daily energy use", "" + energyMail + energyUnits)
end
FWIW, I just struggled through a rounding-based issue so I thought I’d post it here.
I was trying to do a linear interpolation for setting my thermostat temperature based on a few different factors. However, I ultimately wanted to set it to a whole number, not a decimal, hence the rounding. Here’s what I ended up with:
var Number defaultSetPoint = SetPoint_F.state
var Number setPoint = AwaySetPoint_F.state
var Number outdoorTemp = OutdoorTemperature_F.state
var Number heatPumpCutoffHigh = 40
var Number heatPumpCutoffLow = 28
var multiplier = (heatPumpCutoffHigh - outdoorTemp) / (heatPumpCutoffHigh - heatPumpCutoffLow)
// this ends up being type BigDecimal
var setPointDec = sleepSetPoint + multiplier * (defaultSetPoint - sleepSetPoint)
setPoint = Math::round(setPointDec.floatValue())
sendCommand(Nest_temp_setpoint_f, setPoint)