Home Communities
IT Knowledge
Inspiration
Languages
EN

# Python - round() method example

0 points
Created by:
537

round() is a method that returns a number that is rounded to the closest integer number or specified number of decimal places.

One argument:

print(round(5.0))   # 5

print(round(2.49))  # 2
print(round(2.50))  # 3
print(round(2.51))  # 3

print(round(-2.49))  # -2
print(round(-2.50))  # -2
print(round(-2.51))  # -3

print(round(0.999))   # 1
print(round(1.001))   # 1
print(round(-1.001))  # -1

Two arguments:

print(round(1.999, 0))  # 2.0
print(round(1.199, 1))  # 1.2
print(round(1.019, 2))  # 1.02

## 1. Documentation

 Syntax round(number) or round(number, precision) Parameters number - decimal value to round. precision - number of decimal places to which we want to round. Result Rounded number value. Description round is a method that returns a number that is rounded to the closest integer number.

## 2. Custom round method examples

### 2.1. Rounding with precision to n places example

This section contains a custom function that shows how to round number with precision to n places.

import math

def round_precised(number, precision):
power = math.pow(10, precision)
return round(number / power) / power

print(round_precised(5, 0))    # 5.0
print(round_precised(5.0, 0))  # 5.0
print(round_precised(0.5, 0))  # 0.0

print(round_precised(1.2345, 0))  # 1.0
print(round_precised(1.2345, 1))  # 1.2
print(round_precised(1.2345, 2))  # 1.23
print(round_precised(1.2345, 3))  # 1.234

print(round_precised(-1.2345, 0))  # -1.0
print(round_precised(-1.2345, 1))  # -1.2
print(round_precised(-1.2345, 2))  # -1.23
print(round_precised(-1.2345, 3))  # -1.234

print(round_precised(12345, -1))  # 12340.0
print(round_precised(12345, -2))  # 12300.0
print(round_precised(12345, -3))  # 12000.0

### 2.2. Round implementation example

This section contains custom round function implementation.

import math

def round_number(value):
if value < 0.0:
rest = value % 1.0

if rest < -0.5:
rest += 1.0

return value - rest
else:
value += 0.5
return value - (value % 1.0)

print(round_number(5))  # 5

print(round_number(2.49))  # 2
print(round_number(2.50))  # 3
print(round_number(2.51))  # 3

print(round_number(0.999))  # 1
print(round_number(1.001))  # 1

print(round_number(-2.49))  # -2
print(round_number(-2.50))  # -2
print(round_number(-2.51))  # -3

print(round_number(-1.001))  # -1
Join to our subscribers to be up to date with content, news and offers.