Skip to content

Commit 9546390

Browse files
authored
Berry add math.round (#21602)
* Berry add `math.round` * add unit tests * math.roung() returns real
1 parent e4bf2a5 commit 9546390

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ All notable changes to this project will be documented in this file.
99
- Matter support for Air Quality sensors (#21559)
1010
- Matter support for bridged Air Quality (#21597)
1111
- HASPmota rounds to nearest int values passed as 'real' (#21599)
12-
- Berry automatic rounding of float to int when calling C mapped functions (#21601)
12+
- Berry automatic rounding of float to int when calling C mapped functions
13+
- Berry add `math.round`
1314

1415
### Breaking Changed
1516

lib/libesp32/berry/src/be_mathlib.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,17 @@ static int m_floor(bvm *vm)
8989
be_return(vm);
9090
}
9191

92+
static int m_round(bvm *vm)
93+
{
94+
if (be_top(vm) >= 1 && be_isnumber(vm, 1)) {
95+
breal x = be_toreal(vm, 1);
96+
be_pushreal(vm, mathfunc(round)(x));
97+
} else {
98+
be_pushreal(vm, (breal)0.0);
99+
}
100+
be_return(vm);
101+
}
102+
92103
static int m_sin(bvm *vm)
93104
{
94105
if (be_top(vm) >= 1 && be_isnumber(vm, 1)) {
@@ -299,6 +310,7 @@ be_native_module_attr_table(math) {
299310
be_native_module_function("abs", m_abs),
300311
be_native_module_function("ceil", m_ceil),
301312
be_native_module_function("floor", m_floor),
313+
be_native_module_function("round", m_round),
302314
be_native_module_function("sin", m_sin),
303315
be_native_module_function("cos", m_cos),
304316
be_native_module_function("tan", m_tan),
@@ -334,6 +346,7 @@ module math (scope: global, depend: BE_USE_MATH_MODULE) {
334346
abs, func(m_abs)
335347
ceil, func(m_ceil)
336348
floor, func(m_floor)
349+
round, func(m_round)
337350
sin, func(m_sin)
338351
cos, func(m_cos)
339352
tan, func(m_tan)

lib/libesp32/berry/tests/math.be

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,17 @@ m_inf2 = {"v": -math.inf}
4444
assert(json.dump(m_inf2) == '{"v":null}')
4545
m_v = {"v": 3.5}
4646
assert(json.dump(m_v) == '{"v":3.5}')
47+
48+
# math.round
49+
assert(math.round(3) == 3)
50+
assert(math.round(3.2) == 3)
51+
assert(math.round(3.5) == 4)
52+
assert(math.round(3.6) == 4)
53+
54+
assert(math.round(-3) == -3)
55+
assert(math.round(-3.2) == -3)
56+
assert(math.round(-3.5) == -4)
57+
assert(math.round(-3.6) == -4)
58+
59+
assert(math.round() == 0)
60+

0 commit comments

Comments
 (0)