Home Assistant Unofficial Reference 2024.12.1
temperature.py
Go to the documentation of this file.
1 """Temperature helpers for Home Assistant."""
2 
3 from __future__ import annotations
4 
5 from numbers import Number
6 
7 from homeassistant.const import PRECISION_HALVES, PRECISION_TENTHS
8 from homeassistant.core import HomeAssistant
9 from homeassistant.util.unit_conversion import TemperatureConverter
10 
11 
13  hass: HomeAssistant, temperature: float | None, unit: str, precision: float
14 ) -> float | None:
15  """Convert temperature into preferred units/precision for display."""
16  temperature_unit = unit
17  ha_unit = hass.config.units.temperature_unit
18 
19  if temperature is None:
20  return temperature
21 
22  # If the temperature is not a number this can cause issues
23  # with Polymer components, so bail early there.
24  if not isinstance(temperature, Number):
25  raise TypeError(f"Temperature is not a number: {temperature}")
26 
27  if temperature_unit != ha_unit:
28  temperature = TemperatureConverter.converter_factory(temperature_unit, ha_unit)(
29  temperature
30  )
31 
32  # Round in the units appropriate
33  if precision == PRECISION_HALVES:
34  return round(temperature * 2) / 2.0
35  if precision == PRECISION_TENTHS:
36  return round(temperature, 1)
37  # Integer as a fall back (PRECISION_WHOLE)
38  return round(temperature)
float|None display_temp(HomeAssistant hass, float|None temperature, str unit, float precision)
Definition: temperature.py:14