>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
Answer from Harley Holcombe on Stack Overflow
Top answer
1 of 16
3127
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
2 of 16
606

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.

🌐
Sentry
sentry.io › sentry answers › python › how do i parse a string to a float or int?
Python: How to Parse a String to a Float or Int | Sentry
January 30, 2023 - try: not_a_float = float("123.456.789") except ValueError: print("Could not parse string to float") ... Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski. SEE EPISODES ... James W. — October 21, 2022 ... David Y. — May 15, 2023 ... David Y. — March 15, 2023 · Get the current script file's full directory path in Python
Discussions

How to convert string to float ?
a='25$' b=float(''.join([i for i in a if i.isdigit()])) print(b) Use list iteration to take the digits and join the elements in the new list and convert to float value. More on reddit.com
🌐 r/learnpython
42
69
November 14, 2022
ValueError: could not convert string to float
The fast and dirty way is to just split by the comma first. Use ‘string.split(“‘“)’ to turn it into a list of strings, then convert each into floats. More on reddit.com
🌐 r/learnpython
9
6
October 11, 2021
Cannot convert string to float
Because 'a2f6' is not a float? What are trying to do here? More on reddit.com
🌐 r/learnpython
5
2
November 15, 2020
[Python] ValueError Could not convert string to float
Maybe make a function to do it manually? https://stackoverflow.com/questions/31036148/how-to-standardize-normalize-a-date-with-pandas-numpy has some decent answers. Then set the scaler function on it? Looking at the docs. It doesn’t take dates. More on reddit.com
🌐 r/learnprogramming
4
1
March 26, 2022
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-convert-string-to-float
How to Convert String to Float in Python: Complete Guide with Examples | DigitalOcean
Learn how to convert strings to floats in Python using float(). Includes syntax, examples, error handling tips, and real-world use cases for data parsing.
🌐
w3resource
w3resource.com › python-exercises › python-basic-exercise-48.php
Python: Parse a string to Float or Integer - w3resource
May 17, 2025 - # Define a string 'n' containing a numeric value. n = "246.2458" # Convert the string 'n' to a floating-point number and print the result. print(float(n)) # Convert the floating-point number to an integer, truncating any decimal part, and print ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-string-to-float-in-python
Convert String to Float in Python - GeeksforGeeks
July 15, 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.
🌐
PythonHow
pythonhow.com › how › parse-a-string-to-a-float-or-integer
Here is how to parse a string to a float or integer in Python
Our first example would convert the string in the num_string variable to a float and store it in a variable called num. You can then use this variable in your code as needed.Similarly, if you have a string that represents an integer, you can use the int() method to convert it to an int.
Find elsewhere
🌐
Vultr
docs.vultr.com › python › examples › parse-a-string-to-a-float-or-int
Python Program to Parse a String to a Float or Int | Vultr Docs
December 26, 2024 - This code uses the re.findall() method to find all occurrences of patterns that match numbers. It then converts the first found number into a float. Mastering string-to-number conversions in Python is pivotal for data manipulation and ensures that your applications can process and analyze data effectively.
🌐
FavTutor
favtutor.com › blogs › string-to-float-python
6 Ways to Convert String to Float in Python | FavTutor
August 31, 2021 - If you want to convert a string ... be to import the NumPy library using “import NumPy as np.” Later, you can use the “astype” method, an in-build method used to convert the string to a floating-point value in python...
🌐
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 - This is a recipe from PythonFleek. Get the free e-book today! ... Convert strings to numerics, ensuring error-free, precise parsing for advanced computational tasks. def parse_string_to_number(s): try: return int(s) except ValueError: try: return float(s) except ValueError: return None
🌐
Better Stack
betterstack.com › community › questions › python-how-to-parse-string-to-number
How do I parse a string to a float or int in Python? | Better Stack Community
January 26, 2023 - To parse a string to a float in Python, you can use the float() function. This function takes a string as input and returns a floating point number constructed from it.
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-parse-a-string-to-float-or-int-in-python
How to parse a string to float or int in python?
March 24, 2026 - Use int() and float() with try-except blocks for robust general-purpose string-to-number conversion.
🌐
iO Flood
ioflood.com › blog › convert-string-to-float-python
Convert a String to a Float in Python: 3 Easy Methods
December 11, 2023 - So, let’s dive into to String conversion in Python! You can convert a string to a float in Python using the float() function and the syntax, number = float(data).
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python convert string to float
Python Convert String to Float - Spark By {Examples}
May 21, 2024 - How to convert a String to Float in Python? Converting a string to a float is a common operation, especially when working with numerical data stored in
🌐
Altcademy
altcademy.com › blog › how-to-convert-string-to-float-in-python
How to convert string to float in Python - Altcademy.com
June 13, 2023 - Python provides a built-in function called float() that can be used to convert a string to a float.
🌐
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
February 10, 2026 - ... Using the float() function is the most common way to convert string to float in Python. What’s more, it is a built-in function which means it comes with standard Python installation.
🌐
Scaler
scaler.com › home › topics › how to convert string to float in python?
Convert String to Float in Python - Scaler Topics
May 5, 2022 - The first step in using NumPy to convert a string to a float is to import the NumPy library, which would be used to convert the string to the float values. Later, you can convert the string to a floating-point value in Python using the astype method, which is an in-built technique.
🌐
Python Shiksha
python.shiksha › home › tips › how to parse a string to int or float in python
How to Parse a String to int or float in Python - Python Shiksha
July 18, 2021 - Strings are used to represent text information and are enclosed within single or double quotes. ... Int is used to represent whole numbers & integers in python. ... Float is used to represent decimals and floating-point numbers.
🌐
Intellipaat
intellipaat.com › home › blog › how to parse a string to a float or int in python?
How to parse a string to a float or int in Python? - Intellipaat
April 7, 2026 - Using the Python built-in datatype float() we convert the string to float. This built-in function is used to convert an object to a floating point number. ... Code Copied! ... Note: We can also pass the large number without using a long() datatype.