Float fields display

In my custom components there is a float fields

class MyClass:
    ...
    def get_myFloatProperty(self):
        return myFloatVariable;

In lovelace I can see the scary label “3.1500000953674316 W”. But really there is “3.15”. Mathematical rounding does not help, anyway there are undesirable effects like “3.14999999999999”. This is due to nature of float type.

How to control the display at the component level without templates?
2019%2012%2004%20HA

If you’re rendering the value as a string (e.g., setting the state of the entity), then you can use string formatting:

f'{value:0.2f}'

That is, the best available solution will be if my component has two fields - string for beautiful display and digital for graphs?

Every entity has one and only one state, and it will be converted to a string, regardless of what type of value the state() method returns. So, let’s say your Entity-derived class has a _state attribute (like most do.) And let’s say it’s a float. Then your state() method could be:

class MyEntity(Entity):
    """My Entity."""

    ...

    @property
    def state(self):
        """Return the state of the entity."""
        return f'{self._state:0.2f}'

Then it would always have two decimal digits.

If you want to have the full precision available to the user, then you could add that as an attribute. Or vice versa.

I was afraid that after it, the charts will stop working, but everything is ok. Thank you!

1 Like