Skip to content

Commit 1e8ca3a

Browse files
turbinenreiterpfalcon
authored andcommitted
modbuiltins: Implement round() to precision.
1 parent ab14c30 commit 1e8ca3a

3 files changed

Lines changed: 9 additions & 7 deletions

File tree

py/modbuiltins.c

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,6 @@ STATIC mp_obj_t mp_builtin_repr(mp_obj_t o_in) {
431431
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_repr_obj, mp_builtin_repr);
432432

433433
STATIC mp_obj_t mp_builtin_round(mp_uint_t n_args, const mp_obj_t *args) {
434-
// TODO really support second arg
435434
mp_obj_t o_in = args[0];
436435
if (MP_OBJ_IS_INT(o_in)) {
437436
return o_in;
@@ -440,9 +439,11 @@ STATIC mp_obj_t mp_builtin_round(mp_uint_t n_args, const mp_obj_t *args) {
440439
mp_int_t num_dig = 0;
441440
if (n_args > 1) {
442441
num_dig = mp_obj_get_int(args[1]);
443-
if (num_dig > 0) {
444-
mp_not_implemented("round(..., N>0)");
445-
}
442+
mp_float_t val = mp_obj_get_float(o_in);
443+
mp_float_t mult = MICROPY_FLOAT_C_FUN(pow)(10, num_dig);
444+
// TODO may lead to overflow
445+
mp_float_t rounded = MICROPY_FLOAT_C_FUN(round)(val * mult) / mult;
446+
return mp_obj_new_float(rounded);
446447
}
447448
mp_float_t val = mp_obj_get_float(o_in);
448449
mp_float_t rounded = MICROPY_FLOAT_C_FUN(round)(val);

tests/basics/builtin_round.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
tests = [
44
False, True,
5-
0, 1, -1, 10,
5+
0, 1, -1, 10
66
]
77
for t in tests:
88
print(round(t))

tests/float/builtin_float_round.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22

33
# check basic cases
44
tests = [
5-
0.0, 1.0, 0.1, -0.1, 123.4, 123.6, -123.4, -123.6
5+
[0.0], [1.0], [0.1], [-0.1], [123.4], [123.6], [-123.4], [-123.6],
6+
[1.234567, 5], [1.23456, 1], [1.23456, 0], [1234.56, -2]
67
]
78
for t in tests:
8-
print(round(t))
9+
print(round(*t))
910

1011
# check .5 cases
1112
for i in range(11):

0 commit comments

Comments
 (0)