# Python round() Function

The round() function in Python is used to round a floating-point number to a specified number of decimal places.

### Syntax:

The round() function has the following syntax:

round(number[, ndigits])

### Parameters:

The round() function takes two parameters:

• number: is the floating-point number that you want to round.
• ndigits: is an optional parameter that specifies the number of decimal places to which you want to round the number. If ndigits is omitted, number is rounded to the nearest integer.

### Return Value:

The round() function returns the

• nearest integer to the given number if ndigits is not provided
• number rounded off to the ndigits digits if ndigits is provided

## How Does round( ) Work?

When you pass a number to the round() function, it returns a floating-point number that is a rounded version of the specified number, to the specified number of decimal places. If no number of decimal places (ndigits) is specified, it rounds to the nearest integer.

### Rounding Halfway Cases

Python’s round() function uses a rounding strategy known as “round half to even”, which is also known as “bankers’ rounding.” This means that if the number to be rounded is halfway between two numbers, it is rounded to the nearest even number. For example:

print(round(2.5))  # Outputs: 2
print(round(3.5))  # Outputs: 4
print(round(4.5))  # Outputs: 4
print(round(1.5))  # Outputs: 2

This strategy is used to avoid bias in rounding upwards or downwards and is commonly used in financial calculations.

### Round a number to the given number of decimal places

Rounding a number to a given number of decimal places is a common task in programming and data analysis to simplify the representation of a number, reduce noise from insignificant digits, or prepare for presentation or further calculations.

Example:

original_number = 3.14159265
rounded_number = round(original_number, 2)
print(rounded_number)  # Outputs: 3.14

In this example, 3.14159265 is rounded to 3.14 when we specify 2 as the number of decimal places.

### What Happens Internally

Internally, when Python rounds a number, it looks at the digit in the ndigits + 1 place to decide how to round:

• If this digit is less than 5, Python rounds the number down.
• If this digit is 5 or more, Python normally rounds the number up. However, if the digit to be rounded is 5 and it is followed only by zeros or there are no other digits, Python will round to the nearest even number (this is known as “bankers’ rounding”) which we discussed earlier.

### Rounding and Floating-Point Precision

It is important to note that floating-point numbers are represented in computer hardware as base 2 (binary) fractions. Most decimal fractions cannot be represented exactly as binary fractions, which can lead to surprising rounding results:

print(round(2.675, 2))  # May output 2.67 instead of 2.68

This is because the binary floating-point representation of 2.675 is actually slightly less than the decimal value 2.675, and when Python rounds the value to 2 decimal places, it rounds down to 2.67.

### Behavior with Different Data Types

While the round() function is primarily used with floating-point numbers, it can interact with other data types:

• Integers: If round() is used on an integer, the result will be the same integer since there are no decimal places to round.
• Complex Numbers: round() cannot be directly used on complex numbers, as there is no clear definition of rounding for complex numbers.
• Strings: If you try to round a string that represents a number, round() will raise a TypeError. You must first convert the string to a float or an integer.

### Practical Examples of round()

The round() function is a practical utility in Python that is frequently used across different domains. Here are some practical examples to illustrate how you can apply the round() function in various scenarios:

### Basic Rounding:

# Example 1: Rounding to zero decimal places
num = 7.65
rounded_num = round(num)
print(rounded_num)  # Outputs: 8

# Example 2: Rounding to one decimal place
num = 7.65
rounded_num = round(num, 1)
print(rounded_num)  # Outputs: 7.7

# Example 3: Rounding to two decimal places
num = 7.654
rounded_num = round(num, 2)
print(rounded_num)  # Outputs: 7.65

In these examples, we see how round() can be used to round a number to different numbers of decimal places. If no second argument is provided, it rounds to the nearest integer.

### Rounding in Financial Applications:

In finance, currency values are typically rounded to two decimal places. This is a perfect use case for round():

# Example: Rounding currency
price = 49.955
rounded_price = round(price, 2)
print(f"The total price is: ${rounded_price}") # Outputs: The total price is:$49.95

### Rounding for Display Purposes:

When displaying data, you might want to round numbers to make them more readable:

# Example: Rounding for display
temperature = 21.867
rounded_temperature = round(temperature, 1)
print(f"The temperature is {rounded_temperature} degrees Celsius.")
# Outputs: The temperature is 21.9 degrees Celsius.

In this scenario, the temperature is rounded to one decimal place to simplify the display without cluttering it with too many digits.

### Rounding in Lists:

When dealing with lists of numbers, you might want to round all elements:

# Example: Rounding numbers in a list
temperatures = [21.867, 22.342, 19.959, 23.125]
rounded_temperatures = [round(temp, 1) for temp in temperatures]
print(rounded_temperatures)
# Outputs: [21.9, 22.3, 20.0, 23.1]

Here, list comprehension is used to apply the round() function to each element in a list of temperatures.

### Rounding in DataFrames:

In data science, especially with pandas DataFrames, rounding can be used to prepare data for analysis or visualization:

import pandas as pd

# Example: Rounding in a DataFrame
data = {'Value': [3.142857, 2.71828, 1.61803]}
df = pd.DataFrame(data)
df['Rounded_Value'] = df['Value'].round(3)
print(df)

Output:

      Value  Rounded_Value
0  3.142857          3.143
1  2.718280          2.718
2  1.618030          1.618

The round() method in pandas will round the ‘Value’ column to three decimal places and store the result in a new column ‘Rounded_Value’.

### round() vs. Formatting

While round() actually changes the number, string formatting can be used to display a number rounded to a certain number of places without altering the value:

value = 2.34567
print(f"{value:.2f}")  # Outputs: 2.35

In this case, value remains unchanged, but it is presented as a rounded number.

### Consistency with Other Rounding Functions

The round() function’s behavior is consistent with other rounding methods in Python, such as math.floor() and math.ceil(), which round down and up to the nearest whole number, respectively. However, these functions do not provide the option to specify the number of decimal places.

### Conclusion

The round() function is a versatile and useful tool in Python’s arsenal, and understanding its behavior is crucial for precise numerical computations and data formatting. Remembering the idiosyncrasies of floating-point arithmetic and the particularities of the round() function’s algorithm will help prevent common errors and ensure that your rounding is accurate and appropriate for your applications.