Skip to content

Commit 3eed30c

Browse files
committed
Add materials for Python Rounding tutorial
1 parent 3f2ab7e commit 3eed30c

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

python-rounding/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# How to Round Numbers in Python
2+
3+
Here you can find code examples showing different rounding strategies as covered by the Real Python tutorial [How to Round Numbers in Python](https://realpython.com/python-rounding/).

python-rounding/rounding.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import math
2+
3+
4+
def truncate(n, decimals=0):
5+
multiplier = 10**decimals
6+
return int(n * multiplier) / multiplier
7+
8+
9+
def round_up(n, decimals=0):
10+
multiplier = 10**decimals
11+
return math.ceil(n * multiplier) / multiplier
12+
13+
14+
def round_down(n, decimals=0):
15+
multiplier = 10**decimals
16+
return math.floor(n * multiplier) / multiplier
17+
18+
19+
def round_half_up(n, decimals=0):
20+
multiplier = 10**decimals
21+
return math.floor(n * multiplier + 0.5) / multiplier
22+
23+
24+
def round_half_down(n, decimals=0):
25+
multiplier = 10**decimals
26+
return math.ceil(n * multiplier - 0.5) / multiplier
27+
28+
29+
def round_half_away_from_zero(n, decimals=0):
30+
rounded_abs = round_half_up(abs(n), decimals)
31+
return math.copysign(rounded_abs, n)
32+
33+
34+
def round_half_to_even(n, decimals=0):
35+
return round(n, ndigits=decimals)

python-rounding/rounding_numpy.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import numpy as np
2+
3+
4+
def truncate(n, decimals=0):
5+
multiplier = 10**decimals
6+
return np.trunc(n * multiplier) / multiplier
7+
8+
9+
def round_up(n, decimals=0):
10+
multiplier = 10**decimals
11+
return np.ceil(n * multiplier) / multiplier
12+
13+
14+
def round_down(n, decimals=0):
15+
multiplier = 10**decimals
16+
return np.floor(n * multiplier) / multiplier
17+
18+
19+
def round_half_up(n, decimals=0):
20+
multiplier = 10**decimals
21+
return np.floor(n * multiplier + 0.5) / multiplier
22+
23+
24+
def round_half_down(n, decimals=0):
25+
multiplier = 10**decimals
26+
return np.ceil(n * multiplier - 0.5) / multiplier
27+
28+
29+
def round_half_away_from_zero(n, decimals=0):
30+
rounded_abs = round_half_up(np.abs(n), decimals)
31+
return np.copysign(rounded_abs, n)
32+
33+
34+
def round_half_to_even(n, decimals=0):
35+
return np.round(n, decimals=decimals)

0 commit comments

Comments
 (0)