>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
Answer from Harley Holcombe on Stack Overflow
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.

🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-string-to-float-in-python
Convert String to Float in Python - GeeksforGeeks
July 15, 2025 - float() function is an efficient way to convert a string into a floating-point number. As a built-in function, it returns a value of type float and works best with well-formatted numeric strings.
Discussions

How to convert string to float in Python? Why is it a float when directly assigned but a string when a user inputs it? - Stack Overflow
My program prompts the user to input the volume of a sphere. This is one of the example input I have to try: 1.4*1.0e6 This is what I have as the prompt right now: volume = float(input("Enter More on stackoverflow.com
🌐 stackoverflow.com
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
0
2
December 22, 2022
How to convert String to a float? I know for new Float( ) or Float.parseFloat( ) or Float.valueOf( ) tricks, but they don't work.
Float.parseFloat() or Float.valueOf() should work. You'll get a NumberFormatException if the string can't be parsed. From the exception you've posted it looks like you're trying to cast a Float to a String instead of using one of those methods. More on reddit.com
🌐 r/javahelp
13
0
January 13, 2020
Convert String to Float - Questions & Answers - Unity Discussions
Hi I would like to convert a string to float in order to do math operations on it. Here is my line of code where I want to convert the string, which is stored in an array to a float: var mensAverageScore : Float = ar… More on discussions.unity.com
🌐 discussions.unity.com
0
February 16, 2010
🌐
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.

🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-convert-a-string-value-to-float-value-in-java-with-examples
Convert String to Float in Java - GeeksforGeeks
July 12, 2025 - ... // Java Program to convert string to float import java.util.*; class GFG { // Function to convert String to Float public static float StringToFloat(String s) { // Convert string to float // using valueOf() method return Float.valueOf(s); ...
🌐
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...
Find elsewhere
🌐
Centron
centron.de › startseite › how to convert a string to a float in python
How to Convert a String to a Float in Python
February 7, 2025 - Convert a string to a float in Python with the float() function. Explore examples and tips for error-free conversions.
🌐
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 - Here’s how to handle common issues: def safe_float_convert(value): try: return float(value) except ValueError: return None except TypeError: return None # Testing the function with different inputs examples = [ "123.45", # Valid float "invalid", # Invalid string None, # None value "12,345.67", # Comma-separated number ] for example in examples: result = safe_float_convert(example) print(f"Converting {example}: {result}") # Output: # Converting 123.45: 123.45 # Converting invalid: None # Converting None: None # Converting 12,345.67: None
🌐
YourBasic
yourbasic.org › golang › convert-string-to-float
Convert between float and string · YourBasic Go
Use the strconv.ParseFloat function to parse a string as a floating-point number with the precision specified by bitSize: 32 for float32, or 64 for float64. func ParseFloat(s string, bitSize int) (float64, error) When bitSize is 32, the result ...
🌐
Cplusplus
cplusplus.com › reference › string › stof
std::stof - string
String object with the representation of a floating-point number. ... Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value. This parameter can also be a null pointer, in which case it is not used. On success, the function returns the converted floating-point number as a value of type float.
🌐
Baeldung
baeldung.com › home › java › java string › convert string to float and back in java
Convert String to Float and Back in Java | Baeldung
January 8, 2024 - One of the most common ways is to use Float‘s static method: parseFloat(). It will return a primitive float value, represented by the String argument.
🌐
Reddit
reddit.com › r/javahelp › how to convert string to a float? i know for new float( ) or float.parsefloat( ) or float.valueof( ) tricks, but they don't work.
How to convert String to a float? I know for new ...
January 13, 2020 -

I need to put a String in sePrice(float price) setter, but then I get this error: Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: class java.lang.Float cannot be cast to class java.lang.String (java.lang.Float and java.lang.String are in module java.

public class Product {
private SimpleStringProperty name;
private SimpleFloatProperty price;

//I need to to a String here from another method and then convert it to a float.

public void setPrice(float price) {
this.price.set(price);
}
}

I need to use SimpleFloatProperty because I use TableVIew.

🌐
Hacking with Swift
hackingwithswift.com › example-code › language › how-to-convert-a-string-to-a-float
How to convert a string to a float - free Swift example code and tips
May 28, 2019 - let myString = "556" let myFloat = (myString as NSString).floatValue · SPONSORED Dealing with slow iOS compile times? A few small Swift hygiene changes can make a big difference. Break up large functions, add type annotations, and mark classes as final. ... This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions. ... Was this page useful? Let us know! ... Link copied to your pasteboard.
🌐
Unity
discussions.unity.com › questions & answers
Convert String to Float - Questions & Answers - Unity Discussions
February 16, 2010 - Hi I would like to convert a string to float in order to do math operations on it. Here is my line of code where I want to convert the string, which is stored in an array to a float: var mensAverageScore : Float = ar…
🌐
Unity
discussions.unity.com › unity engine
How Do I Convert String To Float? - Unity Engine - Unity Discussions
August 16, 2022 - I wrote my string to the Debug Log and saw that the string contained only a number. So, I tried the Try Catch and found the following error: · Here is my solution: OKtoFire = true; string angle1 = ...
🌐
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 - 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.
🌐
LeetCode
leetcode.com › problems › string-to-integer-atoi
String to Integer (atoi) - LeetCode
Can you solve this real interview question? String to Integer (atoi) - Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: 1. Whitespace: Ignore any leading whitespace (" "). 2. Signedness: Determine ...