Categories
floating-point integer parsing python type-conversion

How do I parse a string to a float or int?

2627

  • How can I convert a str to float?
    "545.2222"  →  545.2222
    
  • How can I convert a str to int?
    "31"        →  31
    

4

  • 17

    As a general rule, if you have an object in Python, and want to convert to that type of object, call type(my_object) on it. The result can usually be called as a function to do the conversion. For instance type(100) results in int, so you can call int(my_object) to try convert my_object to an integer. This doesn’t always work, but is a good “first guess” when coding.

    Jul 5, 2018 at 1:18


  • 6

    int(x) if int(x) == float(x) else float(x)

    – tcpaiva

    Apr 23, 2020 at 0:31

  • 5

    @tcpaiva ValueError: invalid literal for int() with base 10: '1.5'.

    – marcelm

    Oct 14, 2020 at 15:29

  • int(x) if int(float(x)) == float(x) else float(x)

    May 17 at 14:25


2995

>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545

7

  • 12

    just wondering why there is ’04’ in the end? why not simply ’00’? also my current version of python is not having ’04’.

    Aug 17, 2017 at 15:25

  • 73

    @MangatRaiModi Floating point numbers are inherently imperfect for representing decimals. For more, see stackoverflow.com/q/21895756/931277

    – dokkaebi

    Aug 18, 2017 at 21:44

  • 26

    why not simply int(a) but int(float(a)) ?

    Apr 26, 2018 at 14:36

  • 40

    int(a) will give an error that the string isn’t a valid integer: ValueError: invalid literal for int() with base 10: '545.222', but converting from a float to an int is a supported conversion.

    May 7, 2018 at 17:46

  • 4

    You should handle ValueError if you want to be safe

    Sep 9, 2018 at 13:20


586

Python method to check if a string is a float:

def is_float(value):
  try:
    float(value)
    return True
  except:
    return False

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:

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

8

  • 1

    So true becomes 1, that is I inherited from C++ i think

    Sep 11, 2018 at 6:07

  • 7

    I posted this answer in 2014. That UTF-8 glyph for a Chinese 4 has been transforming over the years depending on how stackoverflow developers change up their character encoding scheme upon their microsoft toolstack. It’s a curiosity to see it flip flop over the years as new conversion schemes assert their new ideologies. But yes, Any UTF-8 glyph for a Eastern oriental numeric is not a Python float. Bazinga.

    Dec 4, 2018 at 18:48


  • 6

    how can this be so upvoted, with such a broad exception?

    – E.Serra

    Mar 13, 2019 at 11:38

  • Everything with spaces in between cannot be converted, like "- 12.3" and "45 e6"

    – Simon

    Aug 12, 2019 at 13:43


  • 8

    This except clause should be restricted to TypeError, ValueError

    – wim

    Aug 31, 2019 at 18:11

568

def num(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

6

  • 90

    implicit mixing floats/ints might lead to subtle bugs due to possible loss of precision when working with floats or to different results for / operator on floats/ints. Depending on context it might be preferable to return either int or float, not both.

    – jfs

    Nov 16, 2012 at 14:35

  • 15

    @J.F.Sebastian You are completely correct, but there are times when you want the input to dictate which one it will be. Letting the input dictate which one can work nicely with duck-typing.

    Mar 5, 2013 at 21:29

  • 8

    You can nest another try to throw an exception when it’s not convertible to float.

    – iBug

    Jan 25, 2018 at 12:31

  • 2

    Fails with s = u'\u0000'

    Nov 12, 2018 at 1:26

  • 1

    @iBug Good idea! I recommend throwing ValueError in the corresponding except 😛

    – marcelm

    Feb 5, 2019 at 22:43