openHAB widget - Component 'label' round decimal number


it’s my first attempt to create a widget with the new openHAB toolset and I’m using this widget from the community as template: Multi Sensor (Fibaro/Aeon/Philio/Aeotec) - Add-on Marketplace / UI Widgets - openHAB Community

The component “label” is responsible for displaying the value of an item:

  - component: Label
	  text: =items[(props.item2)].state + " Watt"
		font-size: 18px
		font-weight: 400

Is it possible to round a large decimal number here and if yes, how?
Thanks in advance!

In the widget code you have access to the js Math object and Number object. This gives you several different choices here. The easiest is probably just to parse the state string directly into an integer:

text: =Number.parseInt(items[(props.item2)].state) + " Watt"

That will always just truncate the string at the the decimal point (i.e., even 3.999 will become 3). If you would prefer actual up and down rounding of the number then you can use:

text: =Math.round(items[(props.item2)].state) + " Watt"

and if you would always like the number rounded up to the next higher integer:

text: =Math.ceil(items[(props.item2)].state) + " Watt"
1 Like

Great, thank you very much! Works as expected.

Hi @JustinG,

I am struggling with the same issue. I have a temperature setpoint widget in which I would like to set setpoint with one decimal precision. The following code tend to generate large decimal numbers. Could you please help me to round it to one decimal precision?

actionCommand: =Number(items[props.set_temp_item].state.split(' ')[0]) - 0.1

Thank you,

Numbers in the widget expressions have access to javascript methods such as toFixed:

1 Like

Thank you, I haven’t realised that is JS. :+1:

It is not a full JS implementation. It is just an js-like expression parser. This means there are a lot of things you can’t do, but many of the base js methods are available to you.