Skip to content

Commit

Permalink
Add math.round()
Browse files Browse the repository at this point in the history
  • Loading branch information
s-hadinger committed Jun 9, 2024
1 parent 5ef765f commit 1bb0e75
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/be_mathlib.c
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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)
Expand Down
14 changes: 14 additions & 0 deletions tests/math.be
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit 1bb0e75

Please sign in to comment.