diff --git a/CHANGELOG.md b/CHANGELOG.md index 560a7ec2d..e7c3baa91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,8 @@ All notable changes to this project will be documented in this file. - Matter support for Air Quality sensors (#21559) - Matter support for bridged Air Quality (#21597) - HASPmota rounds to nearest int values passed as 'real' (#21599) -- Berry automatic rounding of float to int when calling C mapped functions (#21601) +- Berry automatic rounding of float to int when calling C mapped functions +- Berry add `math.round` ### Breaking Changed diff --git a/lib/libesp32/berry/src/be_mathlib.c b/lib/libesp32/berry/src/be_mathlib.c index 52abeffd7..17fbfe159 100644 --- a/lib/libesp32/berry/src/be_mathlib.c +++ b/lib/libesp32/berry/src/be_mathlib.c @@ -89,6 +89,17 @@ static int m_floor(bvm *vm) be_return(vm); } +static int m_round(bvm *vm) +{ + if (be_top(vm) >= 1 && be_isnumber(vm, 1)) { + breal x = be_toreal(vm, 1); + be_pushreal(vm, mathfunc(round)(x)); + } else { + be_pushreal(vm, (breal)0.0); + } + be_return(vm); +} + static int m_sin(bvm *vm) { if (be_top(vm) >= 1 && be_isnumber(vm, 1)) { @@ -299,6 +310,7 @@ be_native_module_attr_table(math) { be_native_module_function("abs", m_abs), be_native_module_function("ceil", m_ceil), be_native_module_function("floor", m_floor), + be_native_module_function("round", m_round), be_native_module_function("sin", m_sin), be_native_module_function("cos", m_cos), be_native_module_function("tan", m_tan), @@ -334,6 +346,7 @@ module math (scope: global, depend: BE_USE_MATH_MODULE) { abs, func(m_abs) ceil, func(m_ceil) floor, func(m_floor) + round, func(m_round) sin, func(m_sin) cos, func(m_cos) tan, func(m_tan) diff --git a/lib/libesp32/berry/tests/math.be b/lib/libesp32/berry/tests/math.be index 232ffa285..6ad8b01c1 100644 --- a/lib/libesp32/berry/tests/math.be +++ b/lib/libesp32/berry/tests/math.be @@ -44,3 +44,17 @@ m_inf2 = {"v": -math.inf} assert(json.dump(m_inf2) == '{"v":null}') m_v = {"v": 3.5} assert(json.dump(m_v) == '{"v":3.5}') + +# math.round +assert(math.round(3) == 3) +assert(math.round(3.2) == 3) +assert(math.round(3.5) == 4) +assert(math.round(3.6) == 4) + +assert(math.round(-3) == -3) +assert(math.round(-3.2) == -3) +assert(math.round(-3.5) == -4) +assert(math.round(-3.6) == -4) + +assert(math.round() == 0) +