How to round to 2 decimal places in Python

Learn how to round to 2 decimal places in Python. Explore different methods, tips, real-world applications, and common error debugging.

How to round to 2 decimal places in Python
Published on: 
Fri
Feb 6, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

You will often need to round numbers to two decimal places in Python, a key task for financial calculations and data presentation. Python's built-in functions offer simple ways for precise formatting.

In this article, we'll explore several methods for rounding numbers. We'll also cover practical tips, real-world applications, and debugging advice to help you select the right approach for your specific use case.

Using the round() function

number = 3.14159
rounded = round(number, 2)
print(rounded)--OUTPUT--3.14

Python's built-in round() function is the most direct method for rounding. It accepts two arguments: the number to be rounded and an optional second argument specifying the number of decimal places.

By passing 2 as the second argument, you instruct the function to round the number to two decimal places, turning 3.14159 into 3.14. This approach is perfect for formatting output where you need to control precision, such as when displaying currency or scientific measurements.

Basic formatting methods

While round() alters the number itself, you can also use string formatting to control a number's appearance without changing its underlying value.

Using the format() method

number = 3.14159
formatted = "{:.2f}".format(number)
print(formatted)--OUTPUT--3.14

The string format() method is a powerful tool for presentation. It lets you embed and format values within a string template, where the key is the format specifier inside the curly braces.

  • The : introduces the format spec.
  • .2 sets the precision to two decimal places.
  • f formats the number as a fixed-point value.

Unlike round(), this method returns a formatted string. This makes it ideal for display purposes where you want to present a number in a certain way without altering the original numeric value.

Using f-strings

number = 3.14159
formatted = f"{number:.2f}"
print(formatted)--OUTPUT--3.14

F-strings, or formatted string literals, offer a more modern and readable way to format strings. Introduced in Python 3.6, they let you embed expressions directly inside string literals by prefixing the string with an f.

  • The syntax is concise—you place the variable and format specifier, like {number:.2f}, directly within the string.
  • It uses the same format specifier as the format() method.

This approach is often preferred for its clarity and returns a formatted string, leaving the original number unchanged.

Using the % operator

number = 3.14159
formatted = "%.2f" % number
print(formatted)--OUTPUT--3.14

The % operator offers a classic, C-style way to format strings in Python. It works by pairing a format string, such as "%.2f", with the number you want to format.

  • The format specifier %.2f tells Python to format a number as a floating-point value with two decimal places.
  • The operator connects the format string to the number variable, substituting the placeholder with the formatted value.

While effective, this method is less common in modern code. Developers often favor f-strings or the format() method for their enhanced readability.

Advanced rounding techniques

While the round() function handles everyday tasks, some scenarios require more powerful tools for financial accuracy or large-scale data manipulation.

Using the decimal module

from decimal import Decimal, ROUND_HALF_UP
number = Decimal('3.14159')
rounded = number.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
print(rounded)--OUTPUT--3.14

The decimal module is your go-to for high-precision arithmetic, which is essential for financial applications where floating-point inaccuracies are unacceptable. You create a Decimal object from a string to ensure the value is stored exactly as written, avoiding representation errors.

Rounding is handled with the quantize() method, which offers precise control:

  • It rounds the number to a fixed exponent. Using Decimal('0.01') sets the precision to two decimal places.
  • The rounding argument lets you explicitly define the rounding strategy, giving you more predictable behavior than the standard round() function.

Using numpy for array rounding

import numpy as np
numbers = np.array([3.14159, 2.71828, 1.41421])
rounded = np.round(numbers, 2)
print(rounded)--OUTPUT--[3.14 2.72 1.41]

When you're working with large datasets, the numpy library is a game changer. Its np.round() function is designed for efficiency, allowing you to round every number in an array in a single operation. This is especially useful in data science and scientific computing where performance matters.

  • It takes the array as its first argument and the number of decimal places as the second.
  • The function returns a new numpy array containing the rounded values, leaving the original array untouched.

Creating a custom rounding function

def round_to_2_places(num):
return int(num * 100 + 0.5) / 100

number = 3.14159
print(round_to_2_places(number))--OUTPUT--3.14

For ultimate control, you can write your own rounding function. The round_to_2_places function implements a classic "round half up" strategy, which can be more predictable than Python's default for certain use cases. This approach gives you a custom rounding mechanism tailored to your specific needs.

  • First, it multiplies the number by 100 to shift the decimal point right.
  • Adding 0.5 pushes values of .5 and higher over the integer threshold.
  • The int() function then truncates the decimal, effectively rounding the number.
  • Finally, dividing by 100 shifts the decimal point back.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly.

Instead of piecing together techniques like round(), you can use Agent 4 to build complete applications. Describe what you want to build, and it will handle everything from writing the code and connecting APIs to managing databases and deployment.

  • A simple expense tracker that calculates totals and formats all currency values to two decimal places.
  • A currency conversion tool that pulls the latest rates and displays the converted amount correctly rounded.
  • A scientific data utility that cleans up raw measurement data by rounding all values in a dataset to a consistent precision.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Rounding numbers seems simple, but a few common pitfalls can trip you up if you're not careful.

Fixing unexpected rounding behavior with round()

You might notice that Python's round() function doesn't always round up. For example, round(2.5) returns 2, while round(3.5) returns 4. This is because it uses a "round half to even" strategy, rounding to the nearest even number to reduce statistical bias. While this is fine for many applications, it's not ideal for financial contexts where you typically need to round half up. For that kind of predictable rounding, the decimal module is a much better tool.

Handling format errors with string inputs

Attempting to format a non-numeric string will cause a ValueError. This often happens when you're working with user input that hasn't been validated. Before you apply formatting like f"{value:.2f}", always make sure your input is a number. You can wrap your conversion logic in a try-except block to gracefully handle cases where the input isn't a valid number.

Troubleshooting missing trailing zeros in financial displays

When you round a number like 4.50, the round() function returns the float 4.5, dropping the trailing zero. This can be a problem for displaying currency. To ensure two decimal places are always shown, use string formatting instead. Methods like f-strings with the :.2f specifier will convert the number to a string and preserve those important trailing zeros for a clean, professional display.

Fixing unexpected rounding behavior with round()

The unexpected behavior of round() isn't limited to whole numbers. When working with multiple decimal places, you might encounter rounding that seems incorrect, even when the logic is consistent with Python's design. Take a look at the following example.

value = 2.675
rounded = round(value, 2)
print(rounded) # Will print 2.67 instead of expected 2.68

This happens because of floating-point representation errors. The number 2.675 isn't stored precisely, so round() sees a value slightly less than it should. Check out the code below for a more accurate approach.

from decimal import Decimal, ROUND_HALF_UP
value = Decimal('2.675')
rounded = value.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
print(rounded) # Will print 2.68

To fix this, use the decimal module. By creating a Decimal object from a string like Decimal('2.675'), you bypass floating-point representation errors. The quantize() method then applies precise rounding rules, such as ROUND_HALF_UP, ensuring 2.675 correctly rounds to 2.68. This approach is crucial for financial applications where accuracy is non-negotiable and standard floats can introduce subtle but significant errors.

Handling format errors with string inputs

Applying number formatting like :.2f directly to a string variable won't work, even if the string contains a number. Python will raise a TypeError because the format specifier is for floats, not strings. The code below demonstrates this common mistake.

user_input = "3.14159"
formatted = f"{user_input:.2f}" # TypeError: not a string format specifier
print(formatted)

The :.2f specifier is designed for numbers, but here it's being used on a string variable. Python can't apply numeric formatting to text, which triggers the TypeError. The code below shows how to handle this correctly.

user_input = "3.14159"
formatted = f"{float(user_input):.2f}"
print(formatted)

To fix this TypeError, you must first convert the string to a number before formatting it. The solution is to wrap the variable in the float() function, like float(user_input), directly within the f-string. This explicitly tells Python to treat the string as a floating-point number, allowing the :.2f format specifier to work correctly. Keep an eye out for this error when processing user input or data from files, which are typically read as strings.

Troubleshooting missing trailing zeros in financial displays

When displaying prices, consistency is crucial. The round() function often falls short because it returns a float, which drops the trailing zeros essential for currency. This can lead to inconsistent formatting. The code below shows this issue in action.

prices = [9.5, 10.0, 15.50]
for price in prices:
display = str(round(price, 2))
print(f"${display}") # Outputs: $9.5, $10.0, $15.5

By converting the rounded number to a string with str() inside the loop, the formatting becomes inconsistent. Values like 9.50 are displayed as $9.5, which isn't ideal for currency. Check out the corrected version below.

prices = [9.5, 10.0, 15.50]
for price in prices:
display = f"${price:.2f}"
print(display) # Outputs: $9.50, $10.00, $15.50

The fix is to use an f-string with the :.2f format specifier. This method converts the number to a string and guarantees two decimal places are always shown, even if they are zeros. It correctly formats 9.5 as $9.50 and 10.0 as $10.00. This approach is essential for any application involving currency, ensuring your output looks professional and consistent every time.

Real-world applications

Beyond fixing errors, these rounding techniques are essential for practical tasks like formatting currency and analyzing large datasets.

Formatting currency with the round() function

The round() function is a straightforward tool for financial calculations, such as figuring out the total cost of an item after applying tax.

price = 19.95
tax_rate = 0.08
total = price + (price * tax_rate)
formatted_total = f"${round(total, 2)}"
print(f"Subtotal: ${price}")
print(f"Tax: ${round(price * tax_rate, 2)}")
print(f"Total: {formatted_total}")

This snippet demonstrates a common pattern for handling currency. It first calculates a total by adding a tax, derived from the tax_rate, to the original price.

  • The round() function is used to limit both the tax amount and the final total to two decimal places.
  • An f-string then combines the dollar sign with the rounded number to create a clean, display-ready string like f"${round(total, 2)}".

This approach ensures that all financial values are presented consistently and correctly formatted for display.

Rounding in statistical analysis with pandas

When working with the pandas library for data analysis, you can chain the round() method to statistical summaries to quickly format all the resulting values.

import pandas as pd

data = {'Temperatures': [36.57, 37.21, 36.89, 38.12, 37.45]}
df = pd.DataFrame(data)
stats = df.describe().round(2)
print("Patient temperature statistics (°C):")
print(stats)

This snippet uses the pandas library to analyze a list of temperatures. It begins by creating a DataFrame, which is a powerful table-like structure ideal for handling datasets. The core of the operation is the line df.describe().round(2).

  • The describe() method automatically computes key statistics for your data, including the mean, standard deviation, and quartiles.
  • By chaining .round(2) directly onto it, you efficiently format the entire statistical summary, rounding every calculated value to two decimal places for a clean, presentable output.

Get started with Replit

Put what you've learned into practice. Tell Replit Agent to build "a tip calculator that rounds totals" or "a currency converter that formats output correctly," and it will create the tool for you.

The Agent writes the code, tests for errors, and deploys the app, handling the entire development process. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.