Languages
[Edit]
EN

Python - round() method example

0 points
Created by:
Mark-Rotteveel
327

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.

ResultRounded number value.
Descriptionround 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
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join