Rounding to Two Decimal Places in Python

Learn how to round a number in Python to two decimal places using the round, string formatting, and modulus operators.

In Python, rounding values to two decimal places is often essential, especially when working with precise measurements. For example, think about calculating a loan’s interest. If the result is $1543.6789 then after rounding the result to two decimal places yields $1543.68. This provides a precise amount that is easy to understand and more intuitive. Fractional cents that could make additional computations or reports more difficult are avoided in this way. Choosing the right rounding method can ensure our calculations remain accurate and reliable.

In this tutorial, we’ll explore the importance of rounding numbers to two decimal places in Python, along with various methods and when we can use them.

There are three main ways in which a number can be rounded to two decimal places, which we will discuss in this article:

  • Using the round() function
  • Decimal module
  • String Formatting

Importance of Rounding Decimals

Python is a widely used language for numerical computations. In many situations where numerical precision is crucial, rounding to two decimal places is useful. Here’s a closer look at the reasons behind it and the ways it helps various fields:

  • Financial Accuracy: Values in finance are often only expressed to two decimal places, like dollars and cents. Rounding ensures that data is accurate and formatted consistently by avoiding fractions of cents.
  • Data Readability: Data readability suffers by long decimals. Reports and dashboards with rounded figures are easier to read and understand.
  • Precision Management: Python’s floating-point calculations are prone to small errors. These are decreased by rounding producing more trustworthy figures.
  • Consistency across datasets: Rounding to two decimal places offers a uniform merging and comparing datasets and ensuring consistent results across datasets.

Techniques for rounding decimals in Python

Using the round() function

In Python, we can use the built-in round function to round floating-point numbers to a specified number of decimal places. One of the features of Python’s round() function is its implementation of “round half to even,” also known as “**banker’s rounding.**” In this method, a number is rounded to the nearest even number when it is exactly halfway between two potentially rounded values. For example, round(0.5) returns 0 and round(1.5) returns 2 as output.

Additionally, the round() function can handle both positive and negative values, providing flexibility in various contexts. It is also capable of processing a variety of inputs, including strings and integers that represent numeric values.

Let us have a look at the syntax of the round() function:

round(number, digits) 

Here, number is the floating-point number to be rounded, and digits is the number decimals to use when rounding the number. The Default is 0.”

Let’s look at an example where we round two numbers, num1 and num2 to two decimal places:

num1 = 3.14159
num2 = 2.675
print(f"Rounding {num1} gives: {round (num1, 2)}")
print(f"Rounding {num2} gives: {round (num2, 2)}")

Output:

Rounding 3.14159 gives: 3.14
Rounding 2.675 gives: 2.67

Now, let’s explore the decimal module in Python.

Using the decimal module:

Python’s decimal module supports quick and accurate decimal floating-point calculations. It is mostly used when accuracy is crucial, such as in calculations. It uses a quantize() method to round the decimal number to a specific number of decimal places.

Key Features of the decimal module are the following:

  • Precision control: The decimal module is appropriate for financial applications where accuracy is crucial since it lets us define the level of precision in our computations.
  • Avoiding floating point errors: The decimal module offers precise decimal representation, in contrast to ordinary floating-point types that may introduce rounding errors.

The syntax for the decimal module to create a decimal object that performs a basic operation is shown below:

# Importing the `decimal` class
from decimal import Decimal
# Creating `decimal` object
value = Decimal('10.25')
# Performs arithmetic operations
result = value + Decimal('5.75')

Let’s try to understand the decimal module by looking at the example below:

# Import the decimal module
from decimal import Decimal, ROUND_HALF_UP
# Create Decimal objects
num1 = Decimal ('3.14159')
num2 = Decimal ('2.675')
# Use the quantize method
rounded_num1 = num1.quantize(Decimal ('0.00'), rounding=ROUND_HALF_UP)
rounded_num2 = num2.quantize(Decimal ('0.00'), rounding=ROUND_HALF_UP)
print (f"Rounding {num1} gives: {rounded_num1}")
print (f"Rounding {num2} gives: {rounded_num2}")

Output:

Rounding 3.14159 gives: 3.14 
Rounding 2.675 gives: 2.68 

The above code rounds the decimal number 3.14159 to two decimal places (to 3.14) using the quantize() method from Python’s decimal package. In accordance with standard rounding procedures in financial computations, ROUND_HALF_UP guarantees that numbers precisely halfway between two values round up to the larger value, while Decimal(‘0.01’) indicates that we wish to round to cents.

In addition to the decimal module, for controlling numerical precision, Python offers string formatting. We will explore different string formatting methods, including f-strings, str.format(), and the % .2f approach, and discuss them in detail in the next section.

Using String Formatting

String formatting is a technique used in Python to create strings with dynamic content. By incorporating variables or expressions into a string, we can improve the clarity and accuracy of the output. It is particularly useful for several reasons such as:

  • Dynamic Output: allows us to create strings that can include variable content
  • Readability: Using string formatting makes the code more readable and simpler to understand, as well as how the strings and their data relate to one another.
  • Control Over Precision: String formatting provides the ability to control how numbers are displayed.

Python offers several string formatting options, such as:

Using F-strings (Formatted String Literals)

This method allows us to include variables and expressions directly within the string literals by prefixing the string with the letter f or F. F-strings simplify creating readable strings that incorporate expressions and values directly in line.

The below syntax can be used for formatting floating-point numbers to two decimal places in Python:

f"{value:.2f}"

Here f stands for floating-point format and .2 specifies that we want to round the number to 2 decimal places.

The example below demonstrates using f-strings to format a number to two decimal places. The .2f inside the braces ({}) rounds and displays numbers with two decimal precision:

pi = 3.14159
result = f"{pi: .2f}"
print(result)

Output:

3.14 

Now, let’s explore the str.format() method.

Using str.format() method

To create formatted strings in Python, we can use the str.format() function to replace the specific position with specified values. It is a versatile option for embedding variables or expressions, and it’s particularly useful for setting decimal precision, such as rounding to two decimal places.

Let’s look at an example of how we can use str.format() to round a number to two decimal places:

num = 4.5672
result = "{:.2f}". format(num)
print(result)

Output:

4.57

Let’s look at another approach for string formatting.

Using Modulus (%) Operator

In Python, the % operator, also called modulus operator, We can use this operator for string formatting to round values to a specific number of decimal places. Known as old-style or printf-style formatting, this approach uses format specifiers to control how values are displayed.

Let’s look at an example of string formatting using the % operator:

num = 5.7634
print ("The value of a number rounded to two decimal places is %.2f." % num)

Output:

The value of a number rounded to two decimal places is 5.76 

String formatting can be used effectively for rounding numbers to decimal places without changing their value. By using various string formatting techniques, we can round numbers to a specific number of decimal places that is easier to understand and enhances accuracy.

Comparison of Rounding Approaches in Python

There are several ways to round numbers to specific decimal places in Python, each with unique functionality and performance attributes. The most popular rounding methods are compared below:

Built-in round() function

  • Performance: quick and effective for simple rounding tasks
  • Precision: may introduce floating-point errors, especially with binary representations
  • Usability: easy for fast computations due to its straightforward syntax
  • Use Case: fit for routine rounding jobs when accuracy is not essential

Formatting Techniques for Strings

F-Strings:

  • Performance: fast and efficient
  • Accuracy: produces formatted strings while maintaining the underlying value
  • Usability: syntax that is clear and easy
  • Use Case: perfect for showing figures in an easy-to-understand manner without changing the data

str.format():

  • Performance: Due to method overhead, performance is slightly slower than with f-strings.
  • Accuracy: Similar to f-strings, it is excellent for formatting output.
  • Usability: Easy to use, though the syntax is more complicated than that of f-strings.
  • Use Case: Beneficial for more complex formatting requirements or when using earlier Python versions.

** Modulus(%) Operator:**

  • Performance: Effective but seen as antiquated.
  • Precision: Preserves original values and functions similar to string formatting.
  • Usability: The syntax may be less clear to beginners.
  • Use Case: Ideal for dealing with older codebases or in settings without access to more recent functionality.

decimal Module

  • Performance: Slower than built-in techniques since handling accuracy requires more work.
  • Precision: Prevents floating-point errors and provides accurate decimal representation.
  • Usability: May not be as convenient for basic jobs because it requires importing the module and generating Decimal objects.
  • Use Case: Ideal for scenarios where high precision is required.

Conclusion

Python offers a variety of methods for rounding numbers to two decimal places, each having its own advantages and disadvantages. While the built-in round() function is easy to use for general rounding, it may result in floating-point errors. The modulus operator, str.format() , and f-strings are excellent string formatting tools for presenting data in an understandable manner.

When choosing a rounding method, consider the specific requirements of the application, such as speed, output formatting, or precision.

To learn more about rounding techniques in Python, including various methods and their applications, check out Learn Python 3, our introductory course about Python.

Author

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team