>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
Answer from Harley Holcombe on Stack Overflow
🌐
AskPython
askpython.com › home › python string to float, float to string
Python String to float, float to String - AskPython
February 16, 2023 - Python provides us with the built-in float() method to convert the data type of input from String to float.
Top answer
1 of 16
3120
>>> 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.

Discussions

Python string to float conversion
I don't know what you mean: >>> a = '1721244344.700249000' >>> float(a) 1721244344.700249 These are all the decimal places. Trailing zeros will always be omitted as they are irrelevant. If you want to show them, do so when you output the value: >>> print(a.format("{:.9}")) 1721244344.700249000 More on reddit.com
🌐 r/learnpython
18
5
July 29, 2024
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
Python - decimal places (putting floats into a string) - Stack Overflow
where "0" refers to the first value passed into str.format, ":" says "here comes the format specification", and ".2f" means "floating point number with two decimal places of precision". This is the suggested way of formatting strings now. ... For Python version 3.6 and upwards there is also ... More on stackoverflow.com
🌐 stackoverflow.com
Quick question: Is there a way to get the first three digits of a int without converting it to a string or list?

You probably shouldn't be keeping phone numbers as ints, because they don't behave like ints. You'll never add, subtract, multiply, or divide phone numbers. You will, however, access individual digits of them, so an array is a much more appropriate type. If you absolutely must store them as ints for efficiency reasons (unlikely), then at point of use you should probably just convert them, unless that is too expensive (even more unlikely).

Remember readability is generally more important than minor performance gains, so digits(num)[:3] is much easier to understand than (num-num%le6)/le6 as skier_scott suggests doing.

More on reddit.com
🌐 r/Python
36
16
January 4, 2013
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-string-with-comma-to-float-in-python
Convert String with Comma To Float in Python - GeeksforGeeks
July 23, 2025 - In this example, below Python code converts the numeric string "1,234.56" to a float by removing the comma and then prints the result.
🌐
Plain English
python.plainenglish.io › python-type-casting-made-easy-convert-int-str-float-more-aeba2142df41
Python Type Casting Made Easy — Convert int, str, float & More | by Rabail Zaheer | Python in Plain English
June 22, 2025 - Maybe turn a string "123" into a number you can calculate with? Or a number into text to display in a sentence? That’s exactly what this blog is gonna be all about. I am going to walk you through how to convert between data types in Python using super simple real-world examples.
🌐
IONOS
ionos.com › digital guide › websites › web development › converting python strings to floats
How to convert Python strings to floats - IONOS
January 2, 2025 - In Python, only numerical values can be used in calculations and math operations. We explain how to convert Python strings into floats.
🌐
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.

Find elsewhere
🌐
Scaler
scaler.com › home › topics › how to convert string to float in python?
Convert String to Float in Python - Scaler Topics
May 5, 2022 - When working with terminal or file operations in Python programming, such as reading or writing a file, the user input is a string object. Although you requested a floating-point value, Python's input function returns the user input as a string object. As a result, you must explicitly convert the string to a floating-point value in order to do the required operations.
🌐
Caasify
caasify.com › home › blog › master python string to float conversion: handle errors, locale, and formats
Master Python String to Float Conversion: Handle Errors, Locale, and Formats | Caasify
October 6, 2025 - Introduction Converting strings to floating-point numbers in Python is a key skill for any developer working with numeric data. The built-in float() function is the primary tool for this task, allowing for seamless conversion of strings to numbers.
🌐
Python documentation
docs.python.org › 3 › library › functions.html
Built-in Functions — Python 3.14.3 documentation
February 27, 2026 - The string must not contain whitespace between '+', '-', the 'j' or 'J' suffix, and the decimal number. For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError. More precisely, the input must conform to the complexvalue production rule in the following grammar, after parentheses and leading and trailing whitespace characters are removed: complexvalue: floatvalue | floatvalue ("j" | "J") | floatvalue sign absfloatvalue ("j" | "J")
🌐
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.
🌐
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
For example, if you try to convert a string that contains letters or symbols other than digits and a decimal point (for float()) or only digits (for int()), a ValueError will be raised. In such cases, you should handle the exception in your code to prevent it from crashing. ... Use the polars library Use Selenium to browse a page Load JSON data Build a GUI with FreeSimpleGUI Delete a directory Delete a file Create matplotlib graphs Rename a file Get today's date and convert to string Create a text file and write text on it Read a text file with Python Scrape a Wikipedia page Install dependenci
🌐
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 - The `float()` function handles both regular decimal numbers and scientific notation. It’s worth noting that Python uses dots (.) rather than commas (,) as decimal separators. Real-world data often comes in various formats. Here’s how to handle them: # Removing currency symbols price_string = "$99.99" price = float(price_string.replace("$", "")) print(price) # Output: 99.99 # Converting percentage strings percentage = "85.5%" decimal = float(percentage.strip("%")) / 100 print(decimal) # Output: 0.855 # Handling thousand separators large_number = "1,234,567.89" cleaned_number = float(large_number.replace(",", "")) print(cleaned_number) # Output: 1234567.89
🌐
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 - By the end, you’ll understand the best practices for handling any string-to-float conversion task. Python’s built-in float() function handles most string-to-float conversions, including integers, decimals, negative numbers, scientific notation, and strings with leading/trailing whitespace.
🌐
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.

🌐
Python
docs.python.org › 3 › library › string.html
string — Common string operations
This option is only valid for integer, float and complex types. For integers, when binary, octal, or hexadecimal output is used, this option adds the respective prefix '0b', '0o', '0x', or '0X' to the output value. For float and complex the alternate form causes the result of the conversion to always contain a decimal-point character, even if no digits follow it.
🌐
Pierian Training
pieriantraining.com › home › tutorial: how to convert string to float in python
Convert String to Float in Python: A Beginner's Guide
April 27, 2023 - Discover how to use Python to convert a string into float in a few easy steps. Learn the syntax, detailed examples, and how to handle errors.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › python tutorial › python string to float
Python String to Float | How to Convert String to Float in Python?
April 1, 2023 - In the above code, we have used the same example as above and removed the quotes to make the variable ‘x’ as float since it has decimal point the compiler identifies it as float value and passed it to the variable ‘s’ to convert it into string using the python str() function.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python convert string to float
Python Convert String to Float - Spark By {Examples}
May 21, 2024 - A regular expression is used to find and extract specific patterns of characters from a string. We can use a regular expression to match and extract the float value from a string in Python. We can use the re module and the search() function to find a float value in the string.