summaryrefslogtreecommitdiffstatshomepage
path: root/py/builtin.c
diff options
context:
space:
mode:
authorDamien George <damien.p.george@gmail.com>2014-10-31 11:28:50 +0000
committerDamien George <damien.p.george@gmail.com>2014-10-31 11:28:50 +0000
commit1559a978100762efd84666befd134d5975ae8d4b (patch)
treeb5910a620f1532ae722b865c1f71988e3f4d1e1c /py/builtin.c
parentfa73c9cb25f05ffa6df4c5d15cc754885c3415ff (diff)
downloadmicropython-1559a978100762efd84666befd134d5975ae8d4b.tar.gz
micropython-1559a978100762efd84666befd134d5975ae8d4b.zip
py: Add builtin round function.
Addresses issue #934.
Diffstat (limited to 'py/builtin.c')
-rw-r--r--py/builtin.c23
1 files changed, 22 insertions, 1 deletions
diff --git a/py/builtin.c b/py/builtin.c
index 133473d019..77b58575ae 100644
--- a/py/builtin.c
+++ b/py/builtin.c
@@ -448,9 +448,30 @@ STATIC mp_obj_t mp_builtin_repr(mp_obj_t o_in) {
vstr_free(vstr);
return s;
}
-
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_repr_obj, mp_builtin_repr);
+STATIC mp_obj_t mp_builtin_round(mp_obj_t o_in) {
+ // TODO support second arg
+ if (MP_OBJ_IS_INT(o_in)) {
+ return o_in;
+ }
+#if MICROPY_PY_BUILTINS_FLOAT
+ mp_float_t val = mp_obj_get_float(o_in);
+ mp_float_t rounded = MICROPY_FLOAT_C_FUN(round)(val);
+ mp_int_t r = rounded;
+ // make rounded value even if it was halfway between ints
+ if (val - rounded == 0.5) {
+ r = (r + 1) & (~1);
+ } else if (val - rounded == -0.5) {
+ r &= ~1;
+ }
+#else
+ mp_int_t r = mp_obj_get_int(o_in);
+#endif
+ return mp_obj_new_int(r);
+}
+MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_round_obj, mp_builtin_round);
+
STATIC mp_obj_t mp_builtin_sum(mp_uint_t n_args, const mp_obj_t *args) {
assert(1 <= n_args && n_args <= 2);
mp_obj_t value;