diff --git a/homeassistant/components/mqtt/abbreviations.py b/homeassistant/components/mqtt/abbreviations.py index 8664027e245..cc1f86d285a 100644 --- a/homeassistant/components/mqtt/abbreviations.py +++ b/homeassistant/components/mqtt/abbreviations.py @@ -214,6 +214,7 @@ ABBREVIATIONS = { "stat_val_tpl": "state_value_template", "step": "step", "stype": "subtype", + "sug_dsp_prc": "suggested_display_precision", "sup_dur": "support_duration", "sup_vol": "support_volume_set", "sup_feat": "supported_features", diff --git a/homeassistant/components/mqtt/sensor.py b/homeassistant/components/mqtt/sensor.py index 33c1b9d9fb8..1a8c59ff86e 100644 --- a/homeassistant/components/mqtt/sensor.py +++ b/homeassistant/components/mqtt/sensor.py @@ -60,6 +60,7 @@ _LOGGER = logging.getLogger(__name__) CONF_EXPIRE_AFTER = "expire_after" CONF_LAST_RESET_TOPIC = "last_reset_topic" CONF_LAST_RESET_VALUE_TEMPLATE = "last_reset_value_template" +CONF_SUGGESTED_DISPLAY_PRECISION = "suggested_display_precision" MQTT_SENSOR_ATTRIBUTES_BLOCKED = frozenset( { @@ -104,6 +105,7 @@ _PLATFORM_SCHEMA_BASE = MQTT_RO_SCHEMA.extend( vol.Optional(CONF_LAST_RESET_TOPIC): valid_subscribe_topic, vol.Optional(CONF_LAST_RESET_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, + vol.Optional(CONF_SUGGESTED_DISPLAY_PRECISION): cv.positive_int, vol.Optional(CONF_STATE_CLASS): vol.Any(STATE_CLASSES_SCHEMA, None), vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string, } @@ -226,6 +228,9 @@ class MqttSensor(MqttEntity, RestoreSensor): """(Re)Setup the entity.""" self._attr_device_class = config.get(CONF_DEVICE_CLASS) self._attr_force_update = config[CONF_FORCE_UPDATE] + self._attr_suggested_display_precision = config.get( + CONF_SUGGESTED_DISPLAY_PRECISION + ) self._attr_native_unit_of_measurement = config.get(CONF_UNIT_OF_MEASUREMENT) self._attr_state_class = config.get(CONF_STATE_CLASS) diff --git a/tests/components/mqtt/test_sensor.py b/tests/components/mqtt/test_sensor.py index 1262643253b..ad32773ac5d 100644 --- a/tests/components/mqtt/test_sensor.py +++ b/tests/components/mqtt/test_sensor.py @@ -92,6 +92,7 @@ async def test_setting_sensor_value_via_mqtt_message( "name": "test", "state_topic": "test-topic", "unit_of_measurement": "fav unit", + "suggested_display_precision": 1, } } }, @@ -99,10 +100,12 @@ async def test_setting_sensor_value_via_mqtt_message( await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() - async_fire_mqtt_message(hass, "test-topic", "100") + async_fire_mqtt_message(hass, "test-topic", "100.22") state = hass.states.get("sensor.test") - assert state.state == "100" + # Rounding happens at the frontend + # the state should show the received value + assert state.state == "100.22" assert state.attributes.get("unit_of_measurement") == "fav unit"