Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk2 min

Python String to Float: Convert and Format to Two Decimal Places

Use float() to parse numeric text and .2f to create a string with exactly two digits after the decimal point. Learn how to validate input and when to use Decimal.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Convert the string with float(), then format the number with .2f when you need text with exactly two digits after the decimal point:

text = "12.5"
value = float(text)
formatted = f"{value:.2f}"

print(formatted)  # 12.50

value is a float; formatted is a string. The formatting adds a trailing zero for display without changing the type or arithmetic precision of the float.

As an Amazon Associate I earn from qualifying purchases.

Convert a string and format it to two decimal places

Use Python’s built-in float() to convert valid numeric text, then use an f-string with :.2f to produce a fixed-point string with exactly two digits after the decimal point:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
amount_text = "19.995"
amount = float(amount_text)
print(f"{amount:.2f}")

The output is 20.00. In the format specifier, .2 requests two digits of precision and f selects fixed-point formatting. Python documents f precision as the number of digits following the decimal point. Python format specification

You can use the format() built-in for the same result:

formatted = format(float("19.995"), ".2f")

Keep the number separate from its formatted text

Formatting creates text; it does not turn the value into a decimal type or limit the float’s underlying arithmetic to two places. Keep the float for calculations and format it at the point where you display or emit a label:

value = float("7.4")
label = f"{value:.2f}"  # "7.40"

print(value + 1)  # numeric calculation
print(label)      # text for display

Use .2f when the requirement is a two-place string. round(value, 2) rounds a numeric value, but it does not guarantee trailing zeroes in its displayed representation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Handle invalid or non-finite input

Unsupported text raises ValueError. If the input may be invalid, catch the error and choose a response that fits your program, such as asking the user to try again or returning a validation result:

def parse_float(text):
    try:
        return float(text)
    except ValueError:
        return None

value = parse_float(user_input)
if value is not None:
    print(f"{value:.2f}")

float() accepts decimal text with an optional sign and surrounding whitespace, as well as exponent notation such as "1e-003". It also accepts spellings of NaN and infinity, so successful conversion alone does not establish that a value is finite or within your application’s permitted range. If finite numbers are required, check with math.isfinite() after conversion. Python built-in functions

Use Decimal for decimal-sensitive arithmetic

For money or other calculations where decimal representation and a defined rounding policy matter, use Decimal rather than relying on a float’s display formatting. Construct it from the original string, then use quantize(Decimal("0.01")) to express a two-place quantum:

from decimal import Decimal

amount = Decimal("19.995")
rounded = amount.quantize(Decimal("0.01"))
print(f"{rounded:.2f}")

The rounding result depends on the active Decimal context and its rounding mode; select one that matches your application’s rules. This is an arithmetic choice, unlike formatting a float merely to show two digits. Python decimal documentation

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why .2g does not mean two decimal places

In the format mini-language, f precision counts digits after the decimal point, while g precision counts significant digits and may omit trailing zeroes. Use .2f for two digits after the decimal point; .2g has a different meaning. Python format specification

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.