Need help in removing decimals from a String

Hi,
I need help in removing decimals from a String Item.
I have a rule that combines Temperature, Humidity and Real Feel in one String:

rule "Balcony Summary"
when
    Item BalconyTemperature changed or
    Item BalconyHumidity changed or
    Item FeelTemperature changed
then
    BalconySummary.postUpdate(
        String::format("%s °C / %s %% Feels Like %s °C", BalconyTemperature.state, BalconyHumidity.state, FeelTemperature.state)
    )
end

here is how it looks:

As you can see, the item on its own (real feel) looks fine, but combined in a string has many decimals…
I tried all the usual tricks of %d, %.1f etc, tried to add it in a rule, in a sitemap, all attempts fail. String just doesnt want to accept it. I guess because it’s not a Number.
So far I managed to get all my Number items in order and show how I want…

I think for a case like this you need to work with each Item separately to get them formatted rounded. I don’t think these are QuantityTypes so one way to do it is as follows:

then
    val rawFeel = (FeelTemperature.state as DecimalType).toBigDecimal
    val roundedFeel = rawFeel.round(new java.math.MathContext(2))
    BalconySummary.postUpdate(
        String::format("%s °C / %s %% Feels Like %s °C", BalconyTemperature.state, BalconyHumidity.state, roundedFeel)
    )
end

If it’s a QuantityType it takes a little more.

then
    val rawFeel = new BigDecimal((FeelTemperature.state as Number).doubleValue)
    val roundedFeel = rawFeel.round(new java.math.MathContext(2))
    BalconySummary.postUpdate(
        String::format("%s °C / %s %% Feels Like %s °C", BalconyTemperature.state, BalconyHumidity.state, roundedFeel)
    )
end

Note that the QuantityType version would work for both QuantityTypes and Numbers but it will do some extra work that isn’t necessary for Numbers.

great, thanks, it works. and how would you round it to 1 decimal (if its 50.17xxxxx to make it 50.2) ?
yes its a number, not quantity, so using only what you wrote first…

Change the 2 to a 1.

changed math context to a 1 and got Feels Like 5E+1 °C

Full docs for MathContext can be found here.

1 Like

thx, it was (3)