EN
Python - round() method example
0 points
round()
is a method that returns a number that is rounded to the closest integer number or specified number of decimal places.
One argument:
xxxxxxxxxx
1
print(round(5.0)) # 5
2
3
print(round(2.49)) # 2
4
print(round(2.50)) # 3
5
print(round(2.51)) # 3
6
7
print(round(-2.49)) # -2
8
print(round(-2.50)) # -2
9
print(round(-2.51)) # -3
10
11
print(round(0.999)) # 1
12
print(round(1.001)) # 1
13
print(round(-1.001)) # -1
Two arguments:
xxxxxxxxxx
1
print(round(1.999, 0)) # 2.0
2
print(round(1.199, 1)) # 1.2
3
print(round(1.019, 2)) # 1.02
Syntax |
xxxxxxxxxx 1 round(number) or xxxxxxxxxx 1 round(number, precision) |
Parameters |
|
Result | Rounded number value. |
Description | round is a method that returns a number that is rounded to the closest integer number. |
This section contains a custom function that shows how to round number with precision to n
places.
xxxxxxxxxx
1
import math
2
3
4
def round_precised(number, precision):
5
power = math.pow(10, precision)
6
return round(number / power) / power
7
8
9
print(round_precised(5, 0)) # 5.0
10
print(round_precised(5.0, 0)) # 5.0
11
print(round_precised(0.5, 0)) # 0.0
12
13
print(round_precised(1.2345, 0)) # 1.0
14
print(round_precised(1.2345, 1)) # 1.2
15
print(round_precised(1.2345, 2)) # 1.23
16
print(round_precised(1.2345, 3)) # 1.234
17
18
print(round_precised(-1.2345, 0)) # -1.0
19
print(round_precised(-1.2345, 1)) # -1.2
20
print(round_precised(-1.2345, 2)) # -1.23
21
print(round_precised(-1.2345, 3)) # -1.234
22
23
print(round_precised(12345, -1)) # 12340.0
24
print(round_precised(12345, -2)) # 12300.0
25
print(round_precised(12345, -3)) # 12000.0
This section contains custom round function implementation.
xxxxxxxxxx
1
import math
2
3
4
def round_number(value):
5
if value < 0.0:
6
rest = value % 1.0
7
8
if rest < -0.5:
9
rest += 1.0
10
11
return value - rest
12
else:
13
value += 0.5
14
return value - (value % 1.0)
15
16
17
print(round_number(5)) # 5
18
19
print(round_number(2.49)) # 2
20
print(round_number(2.50)) # 3
21
print(round_number(2.51)) # 3
22
23
print(round_number(0.999)) # 1
24
print(round_number(1.001)) # 1
25
26
print(round_number(-2.49)) # -2
27
print(round_number(-2.50)) # -2
28
print(round_number(-2.51)) # -3
29
30
print(round_number(-1.001)) # -1