>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
Answer from Harley Holcombe on Stack Overflow
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ python-convert-string-to-float
How to Convert String to Float in Python: Complete Guide with Examples | DigitalOcean
July 10, 2025 - Use the string replacement method for simple cases or the locale module for more complex, locale-aware applications. Stick with float() for Simplicity: For all standard conversions, the built-in float() function is the most direct, readable, and Pythonic tool for the job.
Top answer
1 of 16
3117
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
2 of 16
605

Python2 method to check if a string is a float:

def is_float(value):
  if value is None:
      return False
  try:
      float(value)
      return True
  except:
      return False

For the Python3 version of is_float see: Checking if a string can be converted to float in Python

A longer and more accurate name for this function could be: is_convertible_to_float(value)

What is, and is not a float in Python may surprise you:

The below unit tests were done using python2. Check it that Python3 has different behavior for what strings are convertable to float. One confounding difference is that any number of interior underscores are now allowed: (float("1_3.4") == float(13.4)) is True

val                   is_float(val) Note
--------------------  ----------   --------------------------------
""                    False        Blank string
"127"                 True         Passed string
True                  True         Pure sweet Truth
"True"                False        Vile contemptible lie
False                 True         So false it becomes true
"123.456"             True         Decimal
"      -127    "      True         Spaces trimmed
"\t\n12\r\n"          True         whitespace ignored
"NaN"                 True         Not a number
"NaNanananaBATMAN"    False        I am Batman
"-iNF"                True         Negative infinity
"123.E4"              True         Exponential notation
".1"                  True         mantissa only
"1_2_3.4"             False        Underscores not allowed
"12 34"               False        Spaces not allowed on interior
"1,234"               False        Commas gtfo
u'\x30'               True         Unicode is fine.
"NULL"                False        Null is not special
0x3fade               True         Hexadecimal
"6e7777777777777"     True         Shrunk to infinity
"1.797693e+308"       True         This is max value
"infinity"            True         Same as inf
"infinityandBEYOND"   False        Extra characters wreck it
"12.34.56"            False        Only one dot allowed
u'ๅ››'                 False        Japanese '4' is not a float.
"#56"                 False        Pound sign
"56%"                 False        Percent of what?
"0E0"                 True         Exponential, move dot 0 places
0**0                  True         0___0  Exponentiation
"-5e-5"               True         Raise to a negative number
"+1e1"                True         Plus is OK with exponent
"+1e1^5"              False        Fancy exponent not interpreted
"+1e1.3"              False        No decimals in exponent
"-+1"                 False        Make up your mind
"(1)"                 False        Parenthesis is bad

You think you know what numbers are? You are not so good as you think! Not big surprise.

Don't use this code on life-critical software!

Catching broad exceptions this way, killing canaries and gobbling the exception creates a tiny chance that a valid float as string will return false. The float(...) line of code can failed for any of a thousand reasons that have nothing to do with the contents of the string. But if you're writing life-critical software in a duck-typing prototype language like Python, then you've got much larger problems.

๐ŸŒ
Cherry Servers
cherryservers.com โ€บ home โ€บ blog โ€บ python โ€บ how to convert string to float in python (6 different ways)
How to Convert String to Float in Python (6 Different Ways) | Cherry Servers
July 25, 2024 - The primary purpose of the ast.literal_eval() function is to evaluate strings containing Python literals. However, it can also be used to convert strings to floats, provided the strings passed to it contain only a floating-point number.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Convert a String to a Number (int, float) in Python | note.nkmk.me
April 29, 2025 - In Python, you can convert a string (str) to a number using int() for an integer or float() for a floating-point number. Convert a string to int: int() Convert a string to float: float() Convert a bin ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ python string to float conversion
r/learnpython on Reddit: Python string to float conversion
July 29, 2024 -

Hi all, I have a string a = '1721244344.700249000', I want to convert it to a floating value.

Float() is returning only 2 places after decimal point. Like 1721244344.7

Is there a way I can convert the entire string to a floating point value and get all the decimal (upto 9 places after decimal point)?

I have to use python v2.7 for this.

Edit: I do not have problem in printing the all 9 decimal places but I need the floating value so that I can subtract another value so that I get the difference with accuracy upto 9 th decimal point.

๐ŸŒ
Jeremy Morgan
jeremymorgan.com โ€บ python โ€บ how-to-convert-a-string-to-a-float-in-python
How to Convert a String to a Float in Python
The eval() function can be dangerous if used with untrusted input, as it can execute any Python code contained in the string. Therefore, it is recommended to use the float() function for converting strings to floats whenever possible.
๐ŸŒ
Medium
medium.com โ€บ @ryan_forrester_ โ€บ converting-strings-to-floats-in-python-a-complete-guide-f0ec19bf30a0
Converting Strings to Floats in Python: A Complete Guide | by ryan | Medium
October 28, 2024 - # Basic conversion price = float("23.45") print(price) # Output: 23.45 print(type(price)) # Output: <class 'float'> # Converting scientific notation scientific_num = float("1.23e-4") print(scientific_num) # Output: 0.000123 ยท The `float()` function ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ convert-string-to-float-in-python
Convert String to Float in Python - GeeksforGeeks
April 26, 2025 - It converts a string into a Decimal object, effectively avoiding common floating-point rounding errors. ... eval() function reads and runs a string as a Python expression. It can turn a numeric string like "33.28" into a float.
Find elsewhere
Top answer
1 of 16
452

I would just use..

try:
    float(element)
except ValueError:
    print("Not a float")

..it's simple, and it works. Note that it will still throw OverflowError if element is e.g. 1<<1024.

Another option would be a regular expression:

import re
if re.match(r'^-?\d+(?:\.\d+)$', element) is None:
    print("Not float")
2 of 16
325

Python3 method to check for float:

def is_float(element: any) -> bool:
    #If you expect None to be passed:
    if element is None: 
        return False
    try:
        float(element)
        return True
    except ValueError:
        return False

Python2 version of the above: How do I parse a string to a float or int?

Always do unit testing. What is and is not a float may surprise you:

Command to parse                        Is it a float?  Comment
--------------------------------------  --------------- ------------
print(isfloat(""))                      False
print(isfloat("1234567"))               True 
print(isfloat("1_2_3.4"))               True        123.4, underscores ignored
print(isfloat("NaN"))                   True        nan is also float
print(isfloat("123.456"))               True
print(isfloat("123.E4"))                True
print(isfloat(".1"))                    True
print(isfloat("6.523537535629999e-07")) True
print(isfloat("6e777777"))              True        This is same as Inf
print(isfloat("-iNF"))                  True
print(isfloat("1.797693e+308"))         True
print(isfloat("infinity"))              True
print(isfloat("1,234"))                 False
print(isfloat("NULL"))                  False       case insensitive
print(isfloat("NaNananana BATMAN"))     False
print(isfloat(",1"))                    False           
print(isfloat("123.EE4"))               False           
print(isfloat("infinity and BEYOND"))   False
print(isfloat("12.34.56"))              False       Two dots not allowed.
print(isfloat("#56"))                   False
print(isfloat("56%"))                   False
print(isfloat("0E0"))                   True
print(isfloat("x86E0"))                 False
print(isfloat("86-5"))                  False
print(isfloat("True"))                  False       Boolean is not a float.   
print(isfloat(True))                    True        Boolean is a float
print(isfloat("+1e1^5"))                False
print(isfloat("+1e1"))                  True
print(isfloat("+1e1.3"))                False
print(isfloat("+1.3P1"))                False
print(isfloat("-+1"))                   False
print(isfloat("(1)"))                   False       brackets not interpreted

Sinking exceptions like this is bad, because killing canaries is bad because the float method can fail for reasons other than user input. Do not be using code like this on life critical software. Also python has been changing its contract on what unicode strings can be promoted to float so expect this behavior of this code to change on major version updates.

๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ python convert string to float
Python Convert String to Float - Spark By {Examples}
May 21, 2024 - The built-in float() function is the easiest and most straightforward way to convert a string to a float in Python. If you need to perform precise decimal calculations, use the decimal module to convert a string to a float.
๐ŸŒ
IONOS
ionos.com โ€บ digital guide โ€บ websites โ€บ web development โ€บ converting python strings to floats
How to convert Python strings to floats - IONOS
January 2, 2025 - If a ValueError occurs when converting the string to a float, the code in the except block is executed. This can happen if the user enters a value that canโ€™t be converted into a float, like a letter. In this case, a message says that the input is invalid and the loop requests valid input again. If you want to convert a Python string to a float with NumPy, you can use the function numpy.float64().
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ how to convert string to float in python?
Convert String to Float in Python - Scaler Topics
May 5, 2022 - ... If we have the string which contains a comma such as 1,2.56, we can not directly convert the string to float using the float() function as there the condition was that the parameter should only be in integer or decimal form, so we would ...
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ string-to-float-python
6 Ways to Convert String to Float in Python | FavTutor
August 31, 2021 - To convert this list of strings into floating-point values, you have to use for loop to iterate through each item of the list. Later, you can use the float() method to convert each item into float value and then append it to the list again.
๐ŸŒ
Flexiple
flexiple.com โ€บ python โ€บ string-to-float-python
Convert string to float in Python - Flexiple Tutorials - Flexiple
In this solution, we use the most common method to convert any data type including a string to float in Python; float().
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Is it legal/valid to use float() to convert a string containing integer to float? - Python Help - Discussions on Python.org
December 22, 2022 - Hi, Iโ€™m wondering if float(โ€˜10โ€™) (or any integer string) can be safely converted using float() to float number. Documentation of float() states that: the input must conform to the following grammar after leading and trailing whitespace characters are removed: sign ::= "+" | "-" infinity ::= "Infinity" | "inf" nan ::= "nan" numeric_value ::= floatnumber | infinity | nan numeric_string ::= [sign] numeric_value where floatnumber, described in Floating point li...
๐ŸŒ
iO Flood
ioflood.com โ€บ blog โ€บ convert-string-to-float-python
Convert a String to a Float in Python: 3 Easy Methods
December 11, 2023 - The float() function is straightforward and easy to use, making it the go-to method for converting strings to floats in Python. However, itโ€™s important to be aware of its limitations.
๐ŸŒ
Replit
replit.com โ€บ home โ€บ discover โ€บ how to convert a string to a float in python
How to convert a string to a float in Python
A list comprehension, [float(num) for num in string_numbers], achieves the same goal. Many developers find this syntax more direct and readable. When standard methods aren't enough, you'll need more advanced strategies for handling tricky data like international number formats or values embedded in messy text. def convert_international_format(number_str): # Convert European format (1.234,56) to US format (1234.56) if "," in number_str and "." in number_str: number_str = number_str.replace(".", "").replace(",", ".") # Convert format with just comma as decimal (1234,56) elif "," in number_str: number_str = number_str.replace(",", ".") return float(number_str) print(convert_international_format("1.234,56")) # European format print(convert_international_format("1234,56")) # Alternative format--OUTPUT--1234.56 1234.56
๐ŸŒ
Medium
medium.com โ€บ @Doug-Creates โ€บ convert-string-to-float-or-int-in-python-0d93ce89d7b1
Convert String to Float or Int in Python | by Doug Creates | Medium
March 24, 2024 - def parse_string_to_number(s): try: return int(s) except ValueError: try: return float(s) except ValueError: return None ยท This technique is widely used by software developers, data scientists, and anyone working with data transformation or input validation in Python. โ€” Function Definition: Defines a function parse_string_to_number that takes a string s as input. โ€” First Try-Except Block: Attempts to convert the string s to an integer using int(s). โ€” Handling ValueError: If converting to an integer fails due to a ValueError, it proceeds to the next try-except block.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-convert-strings-to-floats-in-pandas-dataframe
How to Convert String to Float in Pandas DataFrame - GeeksforGeeks
July 15, 2025 - In this tutorial, we have covered the DataFrame.astype() and pandas.to_numeric() functions to convert string values to float in Pandas DataFrame. We have also shown the method to handle any possible errors you might face. After completing this guide, you will have no problem converting string values to float in a DataFrame. Comment ยท Article Tags: Article Tags: Python ยท