From 232f99892c42e2a8bfee878f85576e7fe319091d Mon Sep 17 00:00:00 2001 From: Raman Gupta <7243222+raman325@users.noreply.github.com> Date: Tue, 20 Oct 2026 22:57:32 -0400 Subject: [PATCH] Keep template remap clamp output within the output range (#187660) Co-authored-by: Claude Opus 5.5 --- .../helpers/template/extensions/math.py | 7 ++++++- tests/helpers/template/extensions/test_math.py | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/homeassistant/helpers/template/extensions/math.py b/homeassistant/helpers/template/extensions/math.py index 4781be7ea058..7822ccc28347 100644 --- a/homeassistant/helpers/template/extensions/math.py +++ b/homeassistant/helpers/template/extensions/math.py @@ -502,4 +502,9 @@ class MathExtension(BaseTemplateExtension): if steps: normalized = round(normalized * steps) / steps - return out_min_num + (normalized * (out_max_num - out_min_num)) + result = out_min_num + (normalized * (out_max_num - out_min_num)) + if edges == "clamp": + # Rounding in the linear map can overshoot the output bounds. + low, high = sorted((out_min_num, out_max_num)) + return max(low, min(high, result)) + return result diff --git a/tests/helpers/template/extensions/test_math.py b/tests/helpers/template/extensions/test_math.py index 8cec6531e4d7..9381d9680ade 100644 --- a/tests/helpers/template/extensions/test_math.py +++ b/tests/helpers/template/extensions/test_math.py @@ -511,6 +511,22 @@ def test_remap(hass: HomeAssistant) -> None: render(hass, case) +@pytest.mark.parametrize( + ("value", "out_min", "out_max", "expected"), + [ + pytest.param(5, 0.3, 0.9, 0.9, id="above_range"), + pytest.param(5, 0.7, 0.1, 0.1, id="above_range_inverted_output"), + pytest.param(5, 72.0, -75.8, -75.8, id="above_range_mixed_sign_output"), + pytest.param(-5, 0.3, 0.9, 0.3, id="below_range"), + ], +) +def test_remap_clamp_stays_within_output_range( + value: float, out_min: float, out_max: float, expected: float +) -> None: + """Test clamp never returns a value outside the output range.""" + assert MathExtension.remap(value, 0, 1, out_min, out_max, edges="clamp") == expected + + def test_remap_with_steps(hass: HomeAssistant) -> None: """Test remap function with steps parameter.""" # Test basic stepping - quantize to 10 steps