Home Resource Centre Python round() Function | Syntax, Applications & More (+Examples)

Python round() Function | Syntax, Applications & More (+Examples)

The round() function in Python programming is used to round a floating-point number to the nearest integer or to a specified number of decimal places. It plays a crucial role in numerical computations where precision is key, offering a simple way to manage rounding.

In this article, we’ll explore how the Python round() function works, its syntax, and how it handles rounding rules. We'll also dive into code examples and demonstrate its functionality in practical coding scenarios.

What Is A round() Function In Python?

The Python round() function is a built-in function that is used to round a floating-point number to a specified number of decimal places. By default, it rounds to the nearest integer, but it can also round to a desired precision by specifying the number of digits.

This simple yet powerful function plays a vital role in scenarios where precise control over numeric data is essential, such as financial or mathematical calculations, scientific measurements, and formatting outputs.

Syntax Of Python round() Function

round(number, ndigits)

Here, 

  • The parameter number represents the number you want to round.
  • The ndigits parameter is an optional argument that specifies the number of decimal places to round the number to. If omitted, it rounds to the nearest integer by default.

For Example:

  • Rounding to the nearest integer:

print(round(5.678)) # Output: 6

  • Rounding to a specific number of decimal places:

print(round(5.678, 2)) # Output: 5.68

Return Value Of Python round() Function

The round() function in Python returns a rounded number based on the input parameters i.e. ndigits:

  • If the ndigits parameter is not provided, the function returns an integer after rounding the number to the nearest whole number.
  • If the ndigits parameter is provided, the function returns a floating-point number rounded to the specified number of decimal places.

Errors And Exceptions In Python round() Function

Python round() function is generally straightforward but can still encounter some errors or exceptions based on its usage. Here are some common issues of this inbuilt-function:

  • TypeError: This occurs when the input to the round() function is of an unsupported type. For Example-

result = round("string") # Raises TypeError

Solution: Ensure the input is a number (either an integer or a floating-point).

  • ValueError: This may arise when the ndigits parameter is not an integer. For Example-

result = round(5.5, "two") # Raises ValueError

Solution: Always ensure that ndigits parameter is an integer.

  • Negative ndigits: While negative values for ndigits are valid, they can cause confusion if not understood correctly. For Example-

result = round(1234.5678, -2) # Output: 1200.0 (rounds to nearest hundred)

Solution: Ensure clarity in what negative values for ndigits will return.

How Does Python round() Function Work?

The working mechanism of Python round() function is as follows:

  1. Input: The function takes two arguments: number (the number to be rounded) and ndigits (optional, specifies the number of decimal places to round to, defaults to 0 for rounding to the nearest integer).
  2. Rounding Logic:

    • If ndigits is positive, the function rounds to the nearest number with ndigits decimal places.
    • If ndigits is negative, the function rounds to the nearest multiple of 10^-ndigits. For example, round(3.14159, -2) rounds to 3.00.
    • If ndigits is 0, the function rounds to the nearest integer.
  3. Tie-breaking: When a number is exactly halfway between two possible rounded values, Python's round() function uses a "round half up" rule. This means it rounds the number away from zero. For example, round(2.5) rounds to 3.

  4. Return Value: The Python round() function will return the rounded number as a floating-point number.

For Example: 

# Examples of the round() function
print(round(3.14159)) # Output: 3 (to nearest integer)
print(round(3.14159, 2)) # Output: 3.14 (to 2 decimal places)

Python round() Function If The Second Parameter Is Missing

The Python round() function rounds a given number to a specified number of decimal places. If the second parameter is missing, the function defaults to rounding the number to the nearest whole integer.

Code Example: 

Output: 

8

Explanation: 

In this example, the round() function takes only the number 7.8 as input. Since no second parameter is provided, it rounds the number to the nearest integer, which is 8.

Python round() Function If The Second Parameter Is Present

The round() function in Python can take two parameters. When the second parameter is provided, it specifies the number of decimal places to round the given number to. The function rounds the number using the "round half to even" strategy, which minimizes rounding bias in calculations.

Code Example: 

Output: 

5.68

Explanation: 

In this example, the round() function rounds 5.6789 to two decimal places, resulting in the output as 5.68.

Python round() Function With Negative Integers

The round() function in Python can also be used with negative integers. When a negative integer is passed as the first argument, the function rounds the number towards zero, just like it does for positive numbers. If the second parameter (ndigits) is specified, it determines the precision of the rounding. If omitted, the function defaults to rounding to the nearest integer.

Code Example: 

Output: 

-5
-3.46

Explanation: 

In this example:

  1. The first call to round(-4.7) will round the negative number to the nearest integer, resulting in an output -5.
  2. The second call, round(-3.4567, 2), will round the number to two decimal places, resulting in an output of -3.46.

Python round() Function With Math Library

The Python round() function  can be used in conjunction with the math module to perform more advanced mathematical operations. While round() is useful for rounding numbers, the math library provides additional mathematical functions that can be used to manipulate numbers before or after rounding. For example, you can use functions like math.floor(), math.ceil(), or math.sqrt() in combination with round() to achieve desired results.

Code Example: 

Output: 

5
6
4.0

Explanation: 

In this code, we use the round() function in combination with functions from the math module:

  1. The math.floor(num) returns the largest integer less than or equal to num. Here, round() is applied to the floored value of 5.9, which results in 5.
  2. The math.ceil(num2) returns the smallest integer greater than or equal to num2. For 5.1, it returns 6, which is then rounded by round().
  3. The math.sqrt(num3) calculates the square root of 16, resulting in 4.0, which is rounded to 4.0 to two decimal places.

Python round() Function With Numpy Module

The Python round() function can also be used alongside the NumPy module, which is popular for numerical computations in Python. NumPy offers an array of mathematical functions that can efficiently perform operations on entire arrays or matrices. When using NumPy, the numpy.round() function provides similar functionality to Python's built-in round(), that allows us to round the elements of NumPy arrays to a specified number of decimal places.

Code Example: 

Output: 

[1.23 2.35 3.46]

Explanation: 

In the above code example, we use the NumPy library to create an array of floating-point numbers and round each element to two decimal places.

Round Up And Round Down Numbers In Python

The Python round() function can both round numbers up or down depending on the decimal value:

  • If the decimal part is greater than or equal to 0.5, the number rounds up to the nearest integer.
  • If the decimal part is less than 0.5, the number rounds down to the nearest integer.

Code Example: 

Output: 

15
15
16
16

Explanation: 

In this code example, we use the round() function to round different numeric values:

  1. round(15) rounds the integer 15, returning 15.
  2. round(15.3) rounds the float 15.3 down to 15, as it is less than 0.5.
  3. round(15.6) rounds 15.6 up to 16, as it is greater than 0.5.
  4. round(15.5) rounds 15.5 to 16, following the rule of rounding to the nearest even number when it is exactly halfway.

Truncation Vs Rounding In Python

In Python, both truncation and rounding are techniques used to manage decimal numbers, but they serve different purposes and behave differently. Truncation involves cutting off a number at a certain decimal place without rounding. On the other hand, rounding is typically used when level of precision and accuracy are important, as it adjusts values based on their significance.

Given below is a comparison between rounding and truncation, highlighting the impact they can have on numerical values:

Aspect Rounding Truncation
Definition Adjusting a number to the nearest specified value. Removing digits beyond a specified point without adjusting.
Mathematical Approach Uses rules to increase or decrease the last digit based on subsequent digits. Cuts off digits without considering their value.
Example Rounding 4.7 results in 5. Truncating 4.7 results in 4.
Behaviour at Halfway Point Rounds to the nearest even number (bankers' rounding) when exactly halfway. Always removes digits, regardless of their value.
Precision Control It provides a more accurate representation by considering subsequent digits. This can lead to less accurate results by simply discarding digits.
Common Use Cases Financial applications and calculations, statistical analysis, and general rounding needs. Data formatting, programming, and applications where precision is not critical.
Impact on Results It can significantly change the final value, especially with larger numbers or more decimal places. This may lead to a loss of precision and accurate calculations without compensating for discarded values.

Practical Applications Of Python round() Function

Python's round() function has various practical applications across different domains. Here are some common use cases of the inbuilt function:

  • Financial Calculations: We can use the Python round() function to round monetary values to two decimal places to represent cents accurately. For Example-

price = 19.995
rounded_price = round(price, 2) # Output: 20.0

  • Statistical Analysis: We can also use the round() function to round the average scores or percentages to make them easier to interpret. For Example-

average_score = 85.456
rounded_score = round(average_score) # Output: 85

  • Data Formatting: The Python round() function is used to round numerical data for display in reports or dashboards, enhancing readability. For Example-

measurement = 23.6789
formatted_measurement = round(measurement, 2) # Output: 23.68

  • Scientific Calculations: Rounding results of calculations to a specific number of significant figures for precision. For Example-

result = 0.0078967
rounded_result = round(result, 3) # Output: 0.008

  • Gaming Applications: Rounding scores or points to enhance user experience and simplify results. For Example-

player_score = 120.4
final_score = round(player_score) # Output: 120

  • Educational Tools: Rounding answers in quizzes or educational applications to ensure simplicity. For Example-

quiz_answer = 3.14159
rounded_answer = round(quiz_answer, 2) # Output: 3.14

  • Performance Metrics: Rounding performance metrics like time or distance for clearer reporting. For Example-

lap_time = 12.4567
rounded_lap_time = round(lap_time, 2) # Output: 12.46

Conclusion

The round() function is a built-in Python function that provides a straightforward and effective way to round numbers to a specified number of decimal places. It's a versatile tool that can be used in various numerical calculations and data processing tasks. By understanding the behavior and applications of the Python round() function, you can enhance your Python programming skills and perform accurate numerical calculations with confidence.

Frequently Asked Questions

Q. How does round() handle tie-breaking cases?

Python's round() function follows the "round half up" convention. This means that if the number is exactly halfway between two integers, it will round up to the nearest integer. For example, round(2.5) will return 3.

Q. What happens if I don't provide the ndigits argument?

When you use the Python round() function without providing the ndigits argument, it defaults to 0, which means the function will round the given number to the nearest integer. For example, round(3.7) will return 4, while round(3.5) will also return 4 due to the "round half away from zero" rule.

This rule ensures that numbers exactly halfway between two integers, such as 2.5 or -2.5, are rounded away from zero, resulting in -3 for round(-2.5). Thus, omitting the ndigits numeric argument effectively simplifies the rounding operation to just finding the nearest whole number, applicable to both positive and negative values.

Q. Can I use round() to round numbers to a specific number of decimal places?

Yes, you can use the ndigits function parameter to specify the desired number of decimal places. For example, round(3.14159, 2) will return 3.14.

Q. Can I use Python round() function with negative numbers?

Yes, you can use the Python round() function with negative numbers. The function works similarly for negative values as it does for positive ones, rounding them to the nearest integer values or to a specified number of decimal values. 

For Example: 

print(round(-3.5)) # Output: -4 (rounds away from zero)
print(round(-3.14159, 2)) # Output: -3.14 (to 2 decimal places)
print(round(-2.6)) # Output: -3 (rounds to nearest integer)
print(round(-2.499)) # Output: -2 (rounds to nearest integer)

Q. How can you achieve precise rounding with the Decimal module in Python?

To achieve precise rounding in Python, you can use the decimal module, which is part of Python's standard library module and provides more control over decimal digits or floating-point arithmetic compared to the built-in round() function. The decimal module allows you to set the precision of operations and define specific rounding behaviors using methods like quantize().

For Example: 

import decimal
from decimal import Decimal, getcontext
# Set precision and rounding mode
getcontext().prec = 3
getcontext().rounding = decimal.ROUND_HALF_UP
# Rounding using quantize()
result = Decimal('3.14159').quantize(Decimal('1.00')) # Round to two decimal places
print(result) # Output: 3.14 

Q. Is there a way to control the rounding behavior in Python?

While the default behavior of round() is "round half up," you can use the math.ceil() and math.floor() rounding functions to round numbers up or down, respectively. These functions are useful when you need more precise control over the rounding process.

  • math.ceil(x) rounds x up to the nearest integer.
  • math.floor(x) rounds x down to the nearest integer.

For Example:

math.ceil(2.3) will return 3.
math.floor(2.3) will return 2.

You might also be interested in reading the following:

  1. Hello, World! Program In Python | 7 Easy Methods (With Examples)
  2. Swap Two Variables In Python- Different Ways | Codes + Explanation
  3. Python Logical Operators, Short-Circuiting & More (With Examples)
  4. Random Number Generator Python Program (16 Ways + Code Examples)
  5. 12 Ways To Compare Strings In Python Explained (With Examples)
  6. Check Palindrome In Python | 8 Methods With Detailed Code Examples
Muskaan Mishra
Technical Content Editor

I’m a Computer Science graduate with a knack for creative ventures. Through content at Unstop, I am trying to simplify complex tech concepts and make them fun. When I’m not decoding tech jargon, you’ll find me indulging in great food and then burning it out at the gym.

TAGS
Python programming language
Updated On: 16 Oct'24, 11:34 AM IST