By default, when you convert a string to a float in Python, it may display many digits after the decimal point.
However, in real-world scenarios like financial calculations or reports, you often need to show numbers with exactly two decimal places.
In this article, I will explain some Python built-in methods to perform the conversion of string to float with 2 decimal places in easy way.
Convert String to Float with 2 Decimal Places in Python
Now I will explain various methods to convert a string to a float with 2 decimal places in Python.
Read How to Convert String to Uppercase in Python?
1. Use float() and round() Functions
The simplest approach combines Python’s built-in float() and round() functions:
# Convert string to float and round to 2 decimal places
price_string = "23.456"
price_float = round(float(price_string), 2)
print(price_float)Output:
23.46I executed the above example code and added the screenshot below.

This method works by first converting the string to a float using float(), then rounding to 2 decimal places using round().
Check out How to Add Line Breaks in Python Strings?
2. Use Python String Formatting
Using string formatting in Python is a simple and effective way to control how numeric values are displayed, especially when converting strings to floats.
# Using f-strings (Python 3.6+)
price_string = "42.8675"
price_float = float(price_string)
formatted_price = f"{price_float:.2f}"
print(formatted_price)
print(type(formatted_price))
# Convert back to float if needed
final_price = float(formatted_price)
print(final_price)
print(type(final_price))Output:
42.87
<class 'str'>
42.87
<class 'float'>I executed the above example code and added the screenshot below.

This method ensures your float values look clean and consistent for display, while still allowing you to convert them back into float type for further calculations when needed.
String Formatting Options
Python offers multiple ways to format strings with decimal precision:
price = 45.6789
# f-string (Python 3.6+)
print(f"{price:.2f}") # Output: 45.68
# str.format() method
print("{:.2f}".format(price)) # Output: 45.68
# % operator (older style)
print("%.2f" % price) # Output: 45.68The string formatting capabilities in Python are efficient and flexible for controlling decimal display.
Read Convert String to Tuple in Python
3. Use Decimal for Precise Calculations
Python Decimal module from the standard library provides more control over rounding behavior and helps avoid floating-point precision issues.
from decimal import Decimal, ROUND_HALF_UP, getcontext
# Set precision
getcontext().prec = 4
# Convert string to Decimal and round
price_string = "19.999"
price_decimal = Decimal(price_string).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
print(price_decimal)
print(type(price_decimal))
# Convert to float if needed
price_float = float(price_decimal)
print(price_float)Output:
20.00
<class 'decimal.Decimal'>
20.0I executed the above example code and added the screenshot below.

When working with financial data or applications where precision is critical, the Decimal module is preferable.
Check out How to Count Words in a String Using Python?
4. Use NumPy for Scientific Applications
If you’re working with scientific or numerical data, Python NumPy offers efficient solutions:
import numpy as np
price_string = "67.8945"
price_float = np.round(float(price_string), 2)
print(price_float) # Output: 67.89NumPy is particularly useful when working with arrays of values that need consistent rounding.
Common Challenges Faced During Conversion of String to Float and Solutions
Let me explain to you some common challenges that you might face during the conversion of string to float with 2 decimal points and also solutions to them.
Read How to Remove Prefixes from Strings in Python?
Handle Invalid Inputs
When converting strings to floats, especially from user input or external data sources, errors can occur if the string isn’t a valid number.
def safe_float_convert(value_str, decimal_places=2):
try:
return round(float(value_str), decimal_places)
except ValueError:
print(f"Error: '{value_str}' cannot be converted to a float")
return None
# Examples
print(safe_float_convert("45.67")) # Output: 45.67
print(safe_float_convert("$45.67")) # Error message and NoneThe safe_float_convert() function uses a try-except block to safely attempt conversion. If the string is invalid, it prints an error and returns None ensuring your program continues running smoothly.
Check out How to Return a String in Python?
Handle Currency Symbols and Commas
Currency values often come formatted with symbols like $ or commas for thousands. These characters must be removed before the value can be converted to a number.
def parse_currency(amount_str):
# Remove currency symbols, commas, and whitespace
cleaned = amount_str.replace('$', '').replace(',', '').strip()
try:
return round(float(cleaned), 2)
except ValueError:
print(f"Error: '{amount_str}' is not a valid currency amount")
return None
# Example
print(parse_currency("$1,234.56")) # Output: 1234.56The parse_currency() function cleans the string and then safely converts it to a float. This is useful for financial data processing, ensuring that formatted currency strings are interpreted as usable numeric values.
Real-World Application: Process Financial Data
This example demonstrates how to process a list of price strings using three different methods: rounding with float, formatting with f-strings, and high-precision conversion using the Decimal class.
price_strings = ["23.45", "67.8", "120.954", "3"]
# Processing with different methods
def process_prices(price_list):
results = {
"raw": [],
"formatted": [],
"decimal": []
}
from decimal import Decimal, ROUND_HALF_UP
for price in price_list:
# Method 1: float + round
raw_float = round(float(price), 2)
results["raw"].append(raw_float)
# Method 2: string formatting
formatted = f"{float(price):.2f}"
results["formatted"].append(formatted)
# Method 3: Decimal
decimal_val = Decimal(price).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
results["decimal"].append(str(decimal_val))
return results
results = process_prices(price_strings)
for method, values in results.items():
print(f"{method}: {values}")Output:
raw: [23.45, 67.8, 120.95, 3.0]
formatted: ['23.45', '67.80', '120.95', '3.00']
decimal: ['23.45', '67.80', '120.95', '3.00']Notice how the different methods handle the same values slightly differently, especially with trailing zeros.
Best Practices
I have listed some best practices based on my experience working with numeric data in Python:
- Be explicit about your needs: Decide whether you need a float for calculations or a formatted string for display
- Understand rounding behavior: Different methods may use different rounding rules.
- Validate input: Always check that your strings can be converted before attempting conversion
- Use Decimal for financial data: This avoids floating-point precision errors
- Consider the display context: For user interfaces, formatted strings may be more appropriate than raw floats
Conclusion
In this article, I have explained how to convert string to float with 2 decimal places in Python. I discussed four important methods to achieve this task, using float() and round() function, using string formatting, using decimals for precise calculation, and using NumPy for scientific applications. I also covered some common challenges and solutions, real-world applications, and best practices.
Related articles you may also like:
- Convert String to Variable in Python
- Convert String to Variable in Python
- Convert String to Path in Python

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.