How to round to 2 decimal places in Python

Learn to round to 2 decimal places in Python. This guide covers methods, real-world applications, tips, and how to debug common errors.

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

You often need to round numbers to two decimal places in Python, especially for financial reports and scientific data. Python offers several direct methods to handle this task with precision.

You'll learn different techniques, from the round() function to f-strings. You will also get practical tips, see real-world applications, and receive advice to debug common rounding issues effectively.

Using the round() function

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

The built-in round() function is the most direct method for this task. It takes two arguments: the number you want to round and the number of decimal places to preserve. By calling round(number, 2), you're telling Python to keep just two digits after the decimal point, making it a quick solution for basic rounding needs.

It’s worth noting that Python’s round() implements "round half to even" logic. This means numbers exactly halfway between two values are rounded to the nearest even digit. While perfect for many statistical applications, you'll need other methods if you require a different rounding strategy.

Basic formatting methods

If you just need to display a number rounded for output without changing its underlying value, Python’s string formatting methods are your best tools.

Using the format() method

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

The string format() method gives you precise control over how numbers appear in your output. It works by using a format specifier within a string to define the presentation style.

  • The :.2f part is the format specifier.
  • The f tells Python to format the number as a float.
  • The .2 sets the precision to exactly two decimal places.

This method is perfect for display purposes since it returns a formatted string without changing the original number's value, which remains available for other calculations.

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. They allow you to embed expressions directly inside string literals, making your code cleaner.

  • You simply prefix the string with an f.
  • Place the variable and format specifier, like {number:.2f}, directly within the string.

This approach is often preferred for its conciseness and clarity. Just like the format() method, it returns a new formatted string without altering the original number's value.

Using the % operator

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

The % operator offers another way to format strings, though it's an older style inherited from the C programming language. You'll often find it in legacy code. It works by using the % symbol to substitute a value into a format specifier string.

  • The %.2f is the format specifier.
  • The f tells Python to treat the number as a float.
  • The .2 limits the output to two decimal places.

This method is purely for display and returns a new string, leaving the original number's value intact.

Advanced rounding techniques

While built-in functions and formatting are great for straightforward cases, you'll sometimes need more powerful tools for financial precision or bulk data operations.

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

For applications like finance where precision is non-negotiable, the decimal module is your best bet. It sidesteps the floating-point inaccuracies of standard floats. You start by creating a Decimal object, ideally from a string, to preserve its exact value.

  • The quantize() method is used to round the number to a fixed exponent.
  • You define the precision by passing Decimal('0.01') for two decimal places.
  • The rounding parameter, such as ROUND_HALF_UP, lets you explicitly define the rounding behavior—a level of control you don't get with 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. It's designed for efficient numerical operations on entire arrays of data.

  • The np.round() function applies rounding to every element in a numpy array simultaneously.
  • You just pass the array and the number of decimal places you want to keep.

This vectorized approach is far more efficient than looping through a standard Python list, making it ideal for data science and scientific computing tasks where performance is key.

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

Sometimes, you need a specific rounding behavior that Python's built-in functions don't offer. Creating a custom function like round_to_2_places() gives you full control. This function implements a classic "round half up" method, which is a common alternative to Python's default.

  • It works by first multiplying the number by 100 to shift the decimal point.
  • Adding 0.5 and converting to an integer truncates the value, effectively rounding it.
  • Finally, dividing by 100 moves the decimal point back to its original position.

Move faster with Replit

Replit is an AI-powered development platform that turns natural language into working applications. With Replit Agent, you can describe what you want to build, and it will create the entire app—from the database and APIs to deployment.

It can take the rounding methods from this article and turn them into production-ready tools. For example, you could ask it to create:

  • A currency conversion utility that uses the decimal module for accurate financial calculations.
  • An e-commerce price calculator that formats final costs to two decimal places using f-strings.
  • A data analysis script that processes a CSV file, rounding all values to two decimal places with numpy.

You just provide the concept, and it handles the rest. Try Replit Agent to turn your own ideas into software, just by describing them.

Common errors and challenges

Even with Python's straightforward tools, you might run into a few common pitfalls when rounding numbers to two decimal places.

  • Unexpected rounding behavior: The built-in round() function can sometimes produce results that seem off, like rounding 2.675 to 2.67. This is due to its "round half to even" strategy and floating-point inaccuracies. For predictable rounding, especially in finance, use the decimal module to specify the exact rounding rule you need.
  • Format errors with strings: You'll get a ValueError if you try to format a string with a numeric formatter like "{:.2f}". Python needs an actual number, not just a string that looks like one. The fix is to convert the string to a number using float() or Decimal() before you format it.
  • Missing trailing zeros: A common headache is when rounding removes a necessary trailing zero, turning $2.50 into 2.5. This happens because round() returns a float, which doesn't store display formatting. The solution is to use a string formatting method like an f-string for your final output, which guarantees two decimal places are always shown.

Fixing unexpected rounding behavior with round()

Python's round() function doesn't always round up as you might traditionally expect. It uses a "round half to even" method, leading to surprising results for numbers ending in 5. Check out the following code to see this in action.

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

The issue is that floating-point numbers can't always represent decimal values perfectly. The number 2.675 is stored as a value slightly less than its true self, causing round() to round down. See how to fix this below.

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. It avoids floating-point errors by handling numbers with exact precision. By creating a Decimal object from a string, like Decimal('2.675'), you preserve its true value.

The quantize() method with ROUND_HALF_UP then ensures that numbers ending in 5 are always rounded up. This approach is crucial for financial applications or any scenario where predictable rounding is a must.

Handling format errors with string inputs

You'll run into a TypeError if you try to apply numeric formatting to a string, even if it contains digits. Format specifiers like :.2f are strictly for numbers. This issue frequently appears with user input. See the error for yourself in the code below.

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

The f-string attempts to apply the .2f format specifier to user_input, but the variable contains a string. Python can't format text as a number, which triggers the error. Check out the corrected code below.

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

The fix is to explicitly convert the string to a number before formatting it. By wrapping the variable in the float() function, you change its type from a string to a floating-point number. Now, the .2f format specifier can work correctly. Keep an eye out for this error when you’re handling input from users or reading data from files, as that data often arrives as text that needs conversion.

Troubleshooting missing trailing zeros in financial displays

When displaying prices, you need to show two decimal places, like $9.50. However, using the round() function can cause issues by dropping trailing zeros, turning a price into something like $9.5. This can make financial reports look unprofessional. The code below demonstrates this problem.

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

The loop converts each number from round() to a string with str(), which doesn't enforce a two-decimal format. This is why $9.50 displays incorrectly as $9.5. Check out the corrected approach 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 solution is to bypass round() for display and use an f-string with the :.2f format specifier instead. This approach formats the number as a string with exactly two decimal places, adding trailing zeros where necessary. It’s the right tool for the job when preparing financial data or any output where consistent decimal formatting is crucial. This ensures prices like $9.50 and $10.00 always appear correctly.

Real-world applications

Now that you can navigate common rounding pitfalls, you can apply these techniques to practical tasks like formatting currency and analyzing statistical data.

Formatting currency with the round() function

The round() function is a practical tool for formatting financial calculations, like a total price with sales tax, for a clean and readable display.

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 first calculates a total by applying an 8% tax_rate to the initial price. The key steps happen during the output phase, where calculation and formatting are combined.

  • The round() function is applied to both the tax amount and the final total to ensure the values have no more than two decimal places.
  • F-strings then embed these rounded numbers directly into a user-friendly string, complete with a dollar sign prefix for clear currency display.

Rounding in statistical analysis with pandas

In data analysis, the pandas library simplifies rounding by letting you apply the round() method directly to your statistical summaries.

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 code uses the pandas library to quickly analyze a list of temperatures. It first organizes the data into a DataFrame, which is a powerful, table-like structure. The magic happens in one line where two methods are chained together.

  • The describe() method generates a full summary of descriptive statistics, including the mean, standard deviation, and quartiles.
  • Then, round(2) is applied to that entire summary, neatly formatting every calculated value to two decimal places for a clean, readable output.

Get started with Replit

Put your new skills to work. Describe a tool to Replit Agent, like “a currency converter using the decimal module for precision” or “a script that cleans a CSV file by rounding all numeric columns with numpy”.

The agent will write the code, test for errors, and deploy the app based on your instructions. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.