For example, I have a CO2 sensor and I have set the State Description in the model to “%.0f ppm”.
Now I have parts of the UI with little space and I just want to have the number alone ("%.0f") there. Same with temperatures, sometimes I want “20°C” and sometimes I only want “20°”.
I have tried setting the pattern in the widget yaml but it does not work:
component: oh-label-card
config:
item: CO2
pattern: "%.0f"
I only found some examples in the forum with date/time formatting but they are suggesting that setting the pattern in the yaml should work.
The trouble is your raw Item state will be something like “20°C”, the units are part of it. You cannot format that text string using pattern %.0f in the UI because the source is not a simple decimal number. (The OH server does jiggery-pokery behind the scenes at the server end when you use pattern at the actual Item)
You’ll have to have more complex UI code to strip or replace units, parse the string to numeric, and format with decimal places.
You are right for Temperature items. They include the unit in the “state” already.
My CO2 sensor has only the number in “state”. In “displayState” I have the formatted number by the pattern from the model state description.
So, there is no easy way to override the pattern in the UI? Why am I seeing posts with a property “pattern” in widgets (all are setting this for Date/Time)?
Or do I really have to use the (ugly) old HAB Panel trick again?
This shouldn’t work, and probably only does because the item being used in the label has the correct formatting on its displayState. If you take a look at where the label is defined in the vue code:
you can see that when a component is a label and is visible all that is done is that a div is created, the class and style configs are applied to it and then the text config is directly inserted into the the div. That’s it. There’s nothing that alters the text.
As rossko has said, if you want to pattern the text that you are displaying, you have to do it in the expression yourself.