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

🌐
Note.nkmk.me
note.nkmk.me › home › python
Convert a String to a Number (int, float) in Python | note.nkmk.me
April 29, 2025 - Built-in Functions - float() — ... print(float('100')) print(type(float('100'))) # 100.0 # <class 'float'> ... By specifying the base as the second argument to int(), you can convert strings in binary, octal, or hexadecimal notation to ...
Discussions

Type conversion from string float value to int is failing
This version of python has been unsupported since 2020, so I would definitely recommend updating to python 3. There is a small learning curve but since you are currently learning it shouldn’t be a problem, and this way you don’t learn anything that’s woefully obsolete More on discuss.python.org
🌐 discuss.python.org
2
0
July 8, 2024
Is there a better way of converting a float string to int?
Nothing’s wrong with your conversion; I just wouldn’t expect that XPATH to stay valid for very long. More on reddit.com
🌐 r/learnpython
4
2
December 18, 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
convert string to float?
The short answer is, you don't, because if you cannot use the float type (it's technically a class and not a function) then there's really no way for you to directly create an instance. While you could do some trickery with ctypes, I'm sure, there's really no point. Even as a practice exercise. ast.literal_eval technically works, too. Just use float. More on reddit.com
🌐 r/learnpython
16
2
September 22, 2022
🌐
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).
🌐
Python Engineer
python-engineer.com › posts › string-to-float
How to convert a string to float/integer and vice versa in Python - Python Engineer
February 9, 2022 - First, the string value needs to be typecasted into a float and then into an integer.
🌐
Python.org
discuss.python.org › python help
Type conversion from string float value to int is failing - Python Help - Discussions on Python.org
July 8, 2024 - I am trying the below code but it is failing. Var = int(‘3.3’) Print(var) Result: Error is the result. But i tried the following code Var = int(‘3’) Print(var) Result: 3 I am using the following version. Versi…
🌐
Reddit
reddit.com › r/learnpython › is there a better way of converting a float string to int?
r/learnpython on Reddit: Is there a better way of converting a float string to int?
December 18, 2022 -

I feel like this code snippet belongs in r/programminghorror ...

    tripool = browser.find_element(By.XPATH,"/html[1]/body[1]/ui-view[1]/main[1]/div[1]/div[1]/ui-view[1]/div[1]/ui-view[1]/div[5]/div[1]/div[1]/section[1]/pools[1]/section[1]/ul[1]/li[6]/span[2]").text
    tripoolint = tripool.replace('$','')
    tripoolint = tripoolint.replace(',','')
    tripoolint = float(tripoolint)
    tripoolint = int(floor(tripoolint))

Have I done this very poorly or is this an acceptable method of converting a string float (example: $1,123.45 to an int: 1123) from a string variable scrapped via selenium.

Any advice on making the code more efficient/easier on the eyes would be appreciated! TIA

Find elsewhere
🌐
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
September 11, 2026 - my_float_str = "13.37" my_int_str = int(float(my_float_str)) print(my_int_str) # will print 13 · Note that float will still throw an error if you try to parse a string with more than one period. For example: float("123.456.789") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: could not convert string to float: '123.456.789'
🌐
YouTube
youtube.com › watch
Convert String Float to Int in Python - YouTube
This programming tutorial explains how to convert string float to int in Python programming language.
Published: July 23, 2024
🌐
Manifoldapp
cuny.manifoldapp.org › read › how-to-code-in-python-3 › section › 517db09e-e5a2-4b02-bd3d-d5406a3b40a8
How To Convert Data Types | How To Code in Python 3 | Manifold @CUNY
Let’s modify the code to include ... 58 in this example. We can also convert the numbers in the example above to float values by using the float() method in place of the int() method....
🌐
GeeksforGeeks
geeksforgeeks.org › convert-string-to-float-in-python
Convert String to Float in Python - GeeksforGeeks
April 26, 2025 - However, developers often encounter challenges, one of which is the "Cannot Convert String To Float" error. This error occurs when attempting to convert a string to a float, but the string's con ... In Python, converting a string to an integer is important for performing mathematical operations, processing user input and efficiently handling data.
🌐
YouTube
youtube.com › watch
How To Turn Float Into Int Python - YouTube
In this python tutorial, we answer the question of how to turn float into int python. We show you 2 different methods on how to convert a float type into an ...
Published: January 18, 2021
🌐
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
🌐
TutorialsPoint
tutorialspoint.com › How-to-convert-float-to-integer-in-Python
How to convert float to integer in Python?
August 23, 2023 - Data type of num: float Converted value and its data type: 39 , type: int · The int() function cannot directly convert a string containing a float.
🌐
Python Guides
pythonguides.com › convert-float-to-int-python
How to Convert Float to Int in Python?
March 20, 2025 - You must first convert user input to float before converting to integer if the input might contain decimal points. Read How to Get File Name Without Extension in Python?
🌐
Replit
replit.com › home › discover › how to convert an int to a string in python
How to convert an int to a string in Python | Replit
April 14, 2026 - This error occurs if you try to join a string and an integer with the + operator. Python requires you to be explicit, so you must first convert the number using str() before concatenation can work. Fixing decimal precision issues in string conversion. When converting floats, you might get more decimal places than you need.
🌐
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
New: Practice Python, JavaScript & SQL with AI feedback — Try ActiveSkill free → × ... # The string to be converted num_string = "3.14159" # Convert the string to a float num = float(num_string) # Print the first result print(num_string) # The string to be converted num_string1 = "42" # Convert the string to an int num = int(num_string1) # Print the second result print(num_string1)
🌐
365 Data Science
365datascience.com › blog › tutorials › python tutorials › how to convert float to int in python
How to Convert Float to Int in Python – 365 Data Science
April 21, 2023 - Int represents integers – either a positive or negative whole number like 3 or 5. Meanwhile, floats (or floating points) are real numbers, such as 4.37 or 55.87. The difference between the 2 is simply the presence of a decimal point. You can find out what your variable is by applying type()in Python:
🌐
Scaler
scaler.com › home › topics › convert float to int in python
Program to Convert Float to Int Python - Scaler Topics
August 22, 2023 - So when calculating efficiency, integer values are always preferred over floating-point values. So for all this process, we use Python inbuilt functions for converting the float value to the integer values, for example int() function, etc.