Add 'method' parameter to forgiving_round method (#21708)

* Add 'method' parameter to forgiving_round method

Fixes #21707

* fix rounding behavior in round() filter

* add test cases for new rounding behaviour
pull/20992/head
Moritz Fey 2019-03-25 02:10:49 +01:00 committed by Robbie Trencheny
parent 548371e94c
commit f272ed3b91
2 changed files with 20 additions and 2 deletions

View File

@ -442,10 +442,18 @@ class TemplateMethods:
return None
def forgiving_round(value, precision=0):
def forgiving_round(value, precision=0, method="common"):
"""Round accepted strings."""
try:
value = round(float(value), precision)
# support rounding methods like jinja
multiplier = float(10 ** precision)
if method == "ceil":
value = math.ceil(float(value) * multiplier) / multiplier
elif method == "floor":
value = math.floor(float(value) * multiplier) / multiplier
else:
# if method is common or something else, use common rounding
value = round(float(value), precision)
return int(value) if precision == 0 else value
except (ValueError, TypeError):
# If value can't be converted to float

View File

@ -97,6 +97,16 @@ class TestHelpersTemplate(unittest.TestCase):
'{{ states.sensor.temperature.state | multiply(10) | round }}',
self.hass).render()
assert '12.7' == \
template.Template(
'{{ states.sensor.temperature.state | round(1, "floor") }}',
self.hass).render()
assert '12.8' == \
template.Template(
'{{ states.sensor.temperature.state | round(1, "ceil") }}',
self.hass).render()
def test_rounding_value_get_original_value_on_error(self):
"""Test rounding value get original value on error."""
assert 'None' == \