- Alias
- and operator
- append()
- Booleans
- Classes
- Code block
- Comments
- Conditions
- Console
- datetime module
- Dictionaries
- enum
- enumerate() function
- Equality operator
- False
- Float
- For loop
- Formatted strings
- Functions
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Index
- Indices
- Inequality operator
- insert()
- Integer
- Less than operator
- Less than or equal to operator
- List sort() method
- Lists
- map() function
- Match statement
- Modules
- None
- or operator
- Parameter
- pop()
- print() function
- range() function
- Regular expressions
- requests Library
- Return
- round() function
- Sets
- String
- String join() method
- String replace() method
- String split() method
- The not operator
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loop
PYTHON
Python round()
: Rounding Numbers in Python
The Python round()
function rounds floating-point numbers to a specified number of decimal places. It provides a simple way to control the precision of numbers in your code.
How to Use round()
in Python
The round()
function takes a number and rounds it to a specified number of decimal places. If no decimal places are specified, it rounds the number to the nearest whole number.
round()
is a built-in function that takes a number and rounds it to a specified number of decimal places. Without an argument to specify the number of digits, round()
rounds the number to the nearest whole number.
round(number, ndigits)
number
: The number you want to round.ndigits
: The number of decimal places to round to (optional). Without it, the number is rounded to the nearest integer.
Basic Usage
print(round(3.14159)) # Outputs: 3
print(round(3.14159, 2)) # Outputs: 3.14
In this example, the first line rounds 3.14159
to the nearest integer (3
), while the second line rounds it to two decimal places (3.14
).
When to Use round()
in Python
Python Rounding to Two Decimals
When displaying numerical results to users, it's common to round numbers for clarity or to meet specific precision requirements. For example, financial applications might round prices to two decimal places.
price = 49.987
rounded_price = round(price, 2)
print(f"Price: ${rounded_price}") # Outputs: Price: $49.99
Python Rounding to the Nearest Integer
The round()
function is also helpful in rounding a floating-point number to the nearest whole number.
number = 15.6
rounded_number = round(number)
print(rounded_number) # Outputs: 16
Python Math Rounding
Using round()
, you can round results in math or other complex calculations, controlling precision and avoiding displaying unnecessary decimal places.
result = 2.718281828459
rounded_result = round(result, 5)
print(rounded_result) # Outputs: 2.71828
Examples of Using Python round()
Rounding in E-commerce Platforms
An e-commerce platform might use the round()
function to calculate the totals of an order. By rounding the total, the platform can ensure customers pay the correct amount to two decimal places.
subtotal = 199.995
total = round(subtotal, 2)
print(f"Total: ${total}") # Outputs: Total: $200.00
Rounding in Data Analysis
A data analytics tool might need to round data points for displaying or reporting purposes. For instance, rounding temperatures or percentages can make the data more accessible to interpret.
average_temperature = 72.56789
rounded_temp = round(average_temperature, 1)
print(f"Average Temperature: {rounded_temp}°F") # Outputs: Average Temperature: 72.6°F
Rounding in Financial Applications
Financial applications often need to round numbers for currency conversions or financial reports. Rounding to two decimal places ensures that monetary values are representable in the financial world.
exchange_rate = 1.253672
rounded_rate = round(exchange_rate, 4)
print(f"Exchange Rate: {rounded_rate}") # Outputs: Exchange Rate: 1.2537
Learn More About Python round()
Python Rounding Floats vs. Integers
Technically, round()
works with floating-point numbers and integers. With integers, however, a positive ndigits
parameter has no effect since integers are already whole numbers.
print(round(150)) # Outputs: 150
print(round(150, 2)) # Outputs: 150 (since it's an integer, `ndigits` doesn't change the result)
Python round()
with Negative Numbers of Digits
Using a negative value for the ndigits
parameter, the round()
function can round a floating-point number or integer to a multiple of 10. In the following example, we round 12345
to the nearest hundred (12300
), simplifying the value.
print(round(12345, -2)) # Outputs: 12300
round()
and Floating-Point Precision Issues
Python’s round()
function works well in many cases. However, using round()
can sometimes lead to unexpected results because of hardware-related storage quirks.
print(round(2.675, 2)) # Outputs: 2.67, not 2.68 due to floating-point representation issues
While using round()
is good enough for most tasks, remember it’s not an excellent choice for decimal arithmetic. For high-precision cases like accounting and scientific calculations, consider using the decimal
module instead.
Using the Python decimal
Module for Decimal Arithmetic
If precision is critical, Python’s decimal
module provides a way to avoid floating-point precision issues. The decimal
module allows you to work with decimal numbers while avoiding the rounding errors of float
numbers.
from decimal import Decimal, ROUND_HALF_UP
# Create Decimal objects instead of using floats
num = Decimal('2.675')
# Use the quantize() method to round to two decimal places with rounding mode ROUND_HALF_UP
rounded_num = num.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
print(rounded_num) # Outputs: 2.68
In this example, Decimal('2.675')
represents precisely 2.675
. The quantize()
method rounds the number to two decimal places. Using the ROUND_HALF_UP
strategy ensures the correct rounding behavior.
Significant benefits of the decimal
module are:
- Exact representation of decimal numbers.
- Unique rounding strategies (e.g.,
ROUND_HALF_UP
,ROUND_DOWN
). - Useful for financial and other applications requiring high precision.
Rounding vs. Floor and Ceiling Functions
While round()
rounds to the nearest integer, the math.floor()
and math.ceil()
functions from the Python math
library allow you always to round down or up, respectively.
import math
number = 5.7
print(math.floor(number)) # Outputs: 5
print(math.ceil(number)) # Outputs: 6
In this example, math.floor()
rounds down to the nearest integer, while math.ceil()
rounds up.
Rounding Lists in Python
If you need to round elements in a list (or array), you can use list comprehensions or libraries like numpy
to handle numerical data efficiently.
numbers = [1.234, 5.6789, 9.8765]
rounded_numbers = [round(num, 2) for num in numbers]
print(rounded_numbers) # Outputs: [1.23, 5.68, 9.88]
For larger datasets, using numy
provides better performance.
import numpy as np
arr = np.array([1.234, 5.6789, 9.8765])
rounded_arr = np.round(arr, 2)
print(rounded_arr) # Outputs: [1.23 5.68 9.88]
In this example, the entire array is rounded to two decimal places using NumPy's round()
function.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.