Skip to content

Commit 55fa7ed

Browse files
committed
-
1 parent fa0eea4 commit 55fa7ed

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

source_py3/python_toolbox/math_tools/misc.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,4 +151,33 @@ def is_integer(x):
151151
except (TypeError, ValueError, OverflowError):
152152
return False
153153
return inted_x == x
154+
155+
156+
def cute_round(x, step=1, up=False):
157+
'''
158+
Round with a chosen step.
159+
160+
Examples:
161+
162+
>>> cute_round(7.456)
163+
7
164+
>>> cute_round(7.456, up=True)
165+
8
166+
>>> cute_round(7.456, step=0.1)
167+
7.4
168+
>>> cute_round(7.456, step=0.1, up=True)
169+
7.5
170+
>>> cute_round(7.456, step=0.2)
171+
7.4
172+
>>> cute_round(7.456, step=0.2, up=True)
173+
7.6
174+
>>> cute_round(7.456, step=0.01)
175+
7.45
176+
>>> cute_round(7.456, step=0.01, up=True)
177+
7.46
178+
179+
'''
180+
div, mod = divmod(x, step)
181+
return (div + bool(mod and up)) * step
182+
154183

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Copyright 2009-2015 Ram Rachum.
2+
# This program is distributed under the MIT license.
3+
4+
from python_toolbox.math_tools import cute_round
5+
6+
def almost_equals(x, y):
7+
return (abs(1-(x / y)) < (10 ** -10))
8+
9+
10+
def test_cute_round():
11+
assert almost_equals(cute_round(7.456), 7)
12+
assert almost_equals(cute_round(7.456, up=True), 8)
13+
assert almost_equals(cute_round(7.456, step=0.1), 7.4)
14+
assert almost_equals(cute_round(7.456, step=0.1, up=True), 7.5)
15+
assert almost_equals(cute_round(7.456, step=0.2), 7.4)
16+
assert almost_equals(cute_round(7.456, step=0.2, up=True), 7.6)
17+
assert almost_equals(cute_round(7.456, step=0.01), 7.45)
18+
assert almost_equals(cute_round(7.456, step=0.01, up=True), 7.46)

0 commit comments

Comments
 (0)