>>> 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.

🌐
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.

Discussions

Is it legal/valid to use float() to convert a string containing integer to float?
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 ... More on discuss.python.org
🌐 discuss.python.org
8
2
December 22, 2022
python - Clean way to convert string to floating point number with specific precision? - Stack Overflow
I'm trying to convert strings of numbers that come from the output of another program into floating point numbers with two forced decimal places (including trailing zeros). Right now I'm convertin... More on stackoverflow.com
🌐 stackoverflow.com
How I convert float to string in this case?
You shouldn't call your variable sum, as that's a name of a built in function: https://docs.python.org/3/library/functions.html#sum Your problem however, stems from trying to add a string to a float. Could you please tell me, what is Adam + 5? Well, you can't, because it makes no mathematical sense. You didn't save the string representation str(sum), so sum never changed to a string What your research found is f-strings and they are very easy to use. Try: print(f"the sum of the values is {sum}") Simply, put an f before a string starts, then any string that you want goes between " and ", while any variables or other values go between { and } More on reddit.com
🌐 r/learnpython
4
2
August 21, 2022
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
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-string-to-float-in-python
Convert String to Float in Python - GeeksforGeeks
July 15, 2025 - ast.literal_eval() function safely evaluates strings that contain Python literals, such as numbers or lists. It can securely convert a numeric 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
February 1, 2025 - In programs that work with various kinds of data, float() is used to ensure that data remains con­sis­tent by con­vert­ing values into a numerical format. To convert Python strings to floats, use float() and enter a valid string as the argument:
🌐
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...
🌐
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.
Find elsewhere
🌐
W3Schools
w3schools.com › python › python_casting.asp
Python Casting
Python is an object-orientated ... classes to define data types, including its primitive types. Casting in python is therefore done using constructor functions: int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing ...
🌐
Stack Overflow
stackoverflow.com › questions › 57262516 › clean-way-to-convert-string-to-floating-point-number-with-specific-precision
python - Clean way to convert string to floating point number with specific precision? - Stack Overflow
I'm a little unclear on what you mean by "floating point number with specific precision". float is a pre-defined type; you don't get to specify the precision. You can format a string to have a "display image" with that precision, and then convert that to the nearest float value.
🌐
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).
🌐
Programming Idioms
programming-idioms.org › idiom › 146 › convert-string-to-floating-point-number › 2739 › python
Convert string to floating point number, in Python
Convert real number to string with 2 decimal places · Cheatsheets · Issues · Report a bug · × · Python · f = float(s) Python · s = u'545,2222' locale.setlocale(locale.LC_ALL, 'de') f = locale.atof(s) Python · f = float(s) Clojure · (parse-double s) Clojure ·
🌐
Altcademy
altcademy.com › blog › how-to-convert-string-to-float-in-python
How to convert string to float in Python
June 13, 2023 - Python provides a built-in function called float() that can be used to convert a string to a float.
🌐
Python
docs.python.org › 3 › builtins › stdtypes.html
Built-in Types — Python 3.15.0 documentation
Two methods support conversion to and from hexadecimal strings. Since Python’s floats are stored internally as binary numbers, converting a float to or from a decimal string usually involves a small rounding error. In contrast, hexadecimal strings allow exact representation and specification of floating-point numbers.
🌐
Mimo
mimo.org › tutorials › python › how-to-convert-string-to-float-in-python
How to Convert String to Float in Python
Use float("3.14") to convert a numeric string to a float. Clean the string first for spaces and separators, then convert. Wrap conversion in try/except ValueError for messy input. Choose one comma strategy, thousands separators and comma decimals differ. Check for empty or whitespace-only strings ...
🌐
Python Guides
pythonguides.com › convert-string-to-float-in-python
Convert String to Float in Python (Commas, ValueError Fix)
1 month ago - To convert a string to a float in Python, pass it to float(): float("19.99") returns 19.99. If the string contains thousands separators, remove them first (float("1,234.5".replace(",", ""))), and wrap the call in try/except ValueError when the ...
🌐
YouTube
youtube.com › watch
Python Program #58 - Convert a String to a Float or Int in Python - YouTube
Python Program #58 - Convert a String to a Float or Int in PythonIn this video by Programming for beginners we will see Python Program to Convert a String to...
Published: July 5, 2023
🌐
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
December 9, 2023 - 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.
🌐
Facebook
facebook.com › groups › selftaughtprogrammers › posts › 1759043631126030
How do i convert string into float in python?
Popular groups · Find communities for you · Over 1 billion people across the globe are using Facebook Groups to explore their favorite topics · Log in · Categories · Science & tech · Travel · Animals · Sports & fitness · Entertainment
🌐
Python
docs.python.org › 3 › library › string.html
string — Common string operations
In addition to the above presentation types, integers can be formatted with the floating-point presentation types listed below (except 'n' and None). When doing so, float() is used to convert the integer to a floating-point number before formatting.
🌐
Reddit
reddit.com › r/learnpython › how i convert float to string in this case?
r/learnpython on Reddit: How I convert float to string in this case?
August 21, 2022 -

I tried

n1=input('First number')
n2=input('Second number')
sum = float(n1) + float(n2)
str(sum)
print('The sum of the values is: ' + sum)

My error is:

TypeError: can only concatenate str (not "float") to str

I tried googling this error and got some answers like print(f' which I didn't really understand, and some others that looked a little complicated, I am very new.

I am trying to improve my googling skills.