From 423acfa93b857a57d6ddbd519a97bc9658ec04a6 Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Mon, 30 Jan 2023 14:31:27 +0100 Subject: [PATCH] Drop minus sign on negative zero (#86939) * Drop minus sign on negative zero * Add tests --- homeassistant/components/sensor/__init__.py | 9 +++++++++ tests/components/sensor/test_init.py | 17 +++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/homeassistant/components/sensor/__init__.py b/homeassistant/components/sensor/__init__.py index 351976db162d..f61be0193f2b 100644 --- a/homeassistant/components/sensor/__init__.py +++ b/homeassistant/components/sensor/__init__.py @@ -9,6 +9,7 @@ from datetime import date, datetime, timedelta, timezone from decimal import Decimal, InvalidOperation as DecimalInvalidOperation import logging from math import ceil, floor, log10 +import re from typing import Any, Final, cast, final from homeassistant.config_entries import ConfigEntry @@ -84,6 +85,8 @@ _LOGGER: Final = logging.getLogger(__name__) ENTITY_ID_FORMAT: Final = DOMAIN + ".{}" +NEGATIVE_ZERO_PATTERN = re.compile(r"^-(0\.?0*)$") + SCAN_INTERVAL: Final = timedelta(seconds=30) __all__ = [ @@ -647,8 +650,14 @@ class SensorEntity(Entity): unit_of_measurement, ) value = f"{converted_numerical_value:.{precision}f}" + # This can be replaced with adding the z option when we drop support for + # Python 3.10 + value = NEGATIVE_ZERO_PATTERN.sub(r"\1", value) elif precision is not None: value = f"{numerical_value:.{precision}f}" + # This can be replaced with adding the z option when we drop support for + # Python 3.10 + value = NEGATIVE_ZERO_PATTERN.sub(r"\1", value) # Validate unit of measurement used for sensors with a device class if ( diff --git a/tests/components/sensor/test_init.py b/tests/components/sensor/test_init.py index e65ae8ae7b8d..89501cf37df2 100644 --- a/tests/components/sensor/test_init.py +++ b/tests/components/sensor/test_init.py @@ -538,6 +538,15 @@ async def test_custom_unit( "29.921", # Native precision is 3 "1013.24", # One digit of precision removed when converting ), + ( + SensorDeviceClass.ATMOSPHERIC_PRESSURE, + UnitOfPressure.INHG, + UnitOfPressure.HPA, + -0.0001, + 3, + "0.000", # Native precision is 3 + "0.00", # One digit of precision removed when converting + ), ], ) async def test_native_precision_scaling( @@ -595,6 +604,14 @@ async def test_native_precision_scaling( "1000.000", "1000.0000", ), + ( + SensorDeviceClass.DISTANCE, + UnitOfLength.KILOMETERS, + 1, + -0.04, + "-0.040", + "0.0", # Make sure minus is dropped + ), ], ) async def test_custom_precision_native_precision(