Berry add `math.round` (#21602)

* Berry add `math.round`

* add unit tests

* math.roung() returns real
This commit is contained in:
s-hadinger 2024-06-09 19:01:15 +02:00 committed by GitHub
parent e4bf2a5c27
commit 9546390a1f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 29 additions and 1 deletions

View File

@ -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 Air Quality sensors (#21559)
- Matter support for bridged Air Quality (#21597) - Matter support for bridged Air Quality (#21597)
- HASPmota rounds to nearest int values passed as 'real' (#21599) - 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 ### Breaking Changed

View File

@ -89,6 +89,17 @@ static int m_floor(bvm *vm)
be_return(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) static int m_sin(bvm *vm)
{ {
if (be_top(vm) >= 1 && be_isnumber(vm, 1)) { 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("abs", m_abs),
be_native_module_function("ceil", m_ceil), be_native_module_function("ceil", m_ceil),
be_native_module_function("floor", m_floor), 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("sin", m_sin),
be_native_module_function("cos", m_cos), be_native_module_function("cos", m_cos),
be_native_module_function("tan", m_tan), be_native_module_function("tan", m_tan),
@ -334,6 +346,7 @@ module math (scope: global, depend: BE_USE_MATH_MODULE) {
abs, func(m_abs) abs, func(m_abs)
ceil, func(m_ceil) ceil, func(m_ceil)
floor, func(m_floor) floor, func(m_floor)
round, func(m_round)
sin, func(m_sin) sin, func(m_sin)
cos, func(m_cos) cos, func(m_cos)
tan, func(m_tan) tan, func(m_tan)

View File

@ -44,3 +44,17 @@ m_inf2 = {"v": -math.inf}
assert(json.dump(m_inf2) == '{"v":null}') assert(json.dump(m_inf2) == '{"v":null}')
m_v = {"v": 3.5} m_v = {"v": 3.5}
assert(json.dump(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)