
👉Python round() Function with Examples
Python’s round() function is a powerful built-in feature designed to round floating-point numbers to the specified number of decimal places. Whether dealing with simple float rounding or advanced financial calculations, understanding this function is crucial for accurate results.
Python round() Function Syntax
round(float_num, num_of_decimals)
Python round() Function Parameters
- float_num: The float number to be rounded.
- num_of_decimals (optional): Number of decimal places to round to. If not specified, defaults to 0, rounding to the nearest integer.
Return Value
- Returns an integer if num_of_decimals is not given.
- Returns a float if num_of_decimals is specified.
Python round() Function Key Notes
- Values >= 5 after the specified decimal point will round up.
- Values < 5 will round down.
Examples of Using round() Function
Example 1: Rounding Float Numbers
float_num1 = 10.60
float_num2 = 10.40
float_num3 = 10.3456
float_num4 = 10.3445
print(“Rounded value (no decimals):”, round(float_num1)) # Output: 11
print(“Rounded value (no decimals):”, round(float_num2)) # Output: 10
print(“Rounded to 2 decimals:”, round(float_num3, 2)) # Output: 10.35
print(“Rounded to 2 decimals:”, round(float_num4, 2)) # Output: 10.34
Example 2: Rounding Integer Values
num = 15
print(“Rounded integer value:”, round(num)) # Output: 15
Example 3: Rounding Negative Numbers
num = -2.8
num1 = -1.5
print(“Rounded value:”, round(num)) # Output: -3
print(“Rounded value:”, round(num1)) # Output: -2
Advanced Rounding Techniques Using NumPy and Decimal Module
Using NumPy round()
import numpy as np
arr = [-0.341111, 1.455098989, 4.232323, -0.3432326, 7.626632, 5.122323]
arr1 = np.round(arr, 2)
print(arr1) # Output: [-0.34 1.46 4.23 -0.34 7.63 5.12]
Using Decimal Module for Precise Rounding
import decimal
round_num = 15.456
final_val1 = decimal.Decimal(round_num).quantize(decimal.Decimal(‘0.00’), rounding=decimal.ROUND_CEILING)
final_val2 = decimal.Decimal(round_num).quantize(decimal.Decimal(‘0.00’), rounding=decimal.ROUND_DOWN)
print(“Using Decimal – ROUND_CEILING:”, final_val1) # Output: 15.46
print(“Using Decimal – ROUND_DOWN:”, final_val2) # Output: 15.45
👉Summary
- Python’s round() function simplifies rounding float and integer values.
- Use NumPy for bulk data rounding and Decimal for precise financial calculations.
Mastering the round() function will help you avoid errors in mathematical calculations and ensure accurate results in Python programming.