2610
  • How can I convert a str to float?
    "545.2222"  →  545.2222
    
  • How can I convert a str to int?
    "31"        →  31
    
Mateen Ulhaq
  • 21,459
  • 16
  • 82
  • 123
Tristan Havelick
  • 63,483
  • 19
  • 53
  • 64
  • 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. – robertlayton Jul 05 '18 at 01:18
  • 6
    `int(x) if int(x) == float(x) else float(x)` – tcpaiva Apr 23 '20 at 00:31
  • 5
    @tcpaiva `ValueError: invalid literal for int() with base 10: '1.5'`. – marcelm Oct 14 '20 at 15:29
  • int(x) if int(float(x)) == float(x) else float(x) – Klaifer Garcia May 17 '22 at 14:25

30 Answers30

2986
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
Harley Holcombe
  • 166,540
  • 15
  • 68
  • 63
  • 12
    just wondering why there is '04' in the end? why not simply '00'? also my current version of python is not having '04'. – Mangat Rai Modi Aug 17 '17 at 15:25
  • 73
    @MangatRaiModi Floating point numbers are inherently imperfect for representing decimals. For more, see https://stackoverflow.com/q/21895756/931277 – dokkaebi Aug 18 '17 at 21:44
  • 26
    why not simply `int(a)` but `int(float(a))` ? – 463035818_is_not_a_number Apr 26 '18 at 14:36
  • 39
    `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. – David Parks May 07 '18 at 17:46
  • 4
    You should handle `ValueError` if you want to be safe – Joe Bobson Sep 09 '18 at 13:20
  • `return int(a) if float(a) == int(float(a)) else float(a)` – gaozhidf Jul 03 '19 at 09:57
  • 2
    @MangatRaiModi python changed it's rounding policy for floating point numbers a while back, it used to use a fixed number of digits, now it uses the "shortest round trip" representation. – plugwash Aug 22 '19 at 03:04
582

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.

Eric Leschinski
  • 135,913
  • 89
  • 401
  • 325
  • 1
    So true becomes 1, that is I inherited from C++ i think – FindOutIslamNow Sep 11 '18 at 06: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. – Eric Leschinski Dec 04 '18 at 18:48
  • 6
    how can this be so upvoted, with such a broad exception? – E.Serra Mar 13 '19 at 11:38
  • Everything with spaces in between cannot be converted, like `"- 12.3"` and `"45 e6"` – Simon Aug 12 '19 at 13:43
  • 8
    This except clause should be restricted to `TypeError, ValueError` – wim Aug 31 '19 at 18:11
  • Instead of `is_convertible_to_float` a better name would be `can_be_float` – godfryd Jul 14 '21 at 13:15
  • `Commas gtfo` - laughed way too hard at this :D – Michal Šrůtek Mar 06 '22 at 13:19
  • IMHO, unless Python parser and `float` type converter behave differently, type casting should be reliable. I bet, all those false -ves that @EricLeschinski posted will go away if you set the right `locale` (i.e., the one the format is meant for). Locale setting is global. For client side code, user must already have the right locale set. For server side code the only workaround I know is to spawn a child Python process (need not be Python, of course). – haridsv May 03 '22 at 15:11
567
def num(s):
    try:
        return int(s)
    except ValueError:
        return float(s)
David Jones
  • 4,163
  • 3
  • 30
  • 43
Javier
  • 58,927
  • 8
  • 76
  • 126
  • 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 '12 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. – TimothyAWiseman Mar 05 '13 at 21:29
  • 8
    You can nest another `try` to throw an exception when it's not convertible to float. – iBug Jan 25 '18 at 12:31
  • 2
    Fails with `s = u'\u0000'` – Matt Hancock Nov 12 '18 at 01:26
  • 1
    @iBug Good idea! I recommend throwing `ValueError` in the corresponding `except` :P – marcelm Feb 05 '19 at 22:43
  • @Matt Why wouldn't it? NUL is not a number. If you want to convert it to `0`, you'll need to go another route, like `int(u'\x00'.encode('hex'), 16)`. – wjandrea Apr 26 '21 at 22:45
154

This is another method which deserves to be mentioned here, ast.literal_eval:

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

That is, a safe 'eval'

>>> import ast
>>> ast.literal_eval("545.2222")
545.2222
>>> ast.literal_eval("31")
31
Stefano
  • 17,175
  • 11
  • 61
  • 79
wim
  • 302,178
  • 90
  • 548
  • 690
  • 13
    this is *not* a good solution to the problem. It works fine in Python 2, but the following happens in Python 3: ```python >>> import ast >>> ast.literal_eval('1-800-555-1212') -2566 >>> ``` To clarify why this is a problem, if you want it to leave phone numbers alone and not assume they are mathematical expressions, then this approach is not for you. – royce3 Jan 16 '18 at 16:14
  • 6
    @royce3 Yeah, that's a good point and users should beware. The behaviour was originally modified in order to address some issues with parsing of complex literals. It's arguably a bug in `ast.literal_eval`, and has been discussed [here](https://stackoverflow.com/q/20748202/674039). – wim Jan 16 '18 at 17:57
  • @royce3 For the record, `ast` will not literal eval that phone number to -2566 anymore in Python 3. It's in the Python 3.7 [changelog](https://docs.python.org/3/whatsnew/3.7.html#changes-in-the-python-api): _`ast.literal_eval()` is now stricter. Addition and subtraction of arbitrary numbers are no longer allowed. (Contributed by Serhiy Storchaka in [bpo-31778](https://github.com/python/cpython/issues/75959))_ – wim Apr 26 '22 at 15:55
82

Localization and commas

You should consider the possibility of commas in the string representation of a number, for cases like float("545,545.2222") which throws an exception. Instead, use methods in locale to convert the strings to numbers and interpret commas correctly. The locale.atof method converts to a float in one step once the locale has been set for the desired number convention.

Example 1 -- United States number conventions

In the United States and the UK, commas can be used as a thousands separator. In this example with American locale, the comma is handled properly as a separator:

>>> import locale
>>> a = u'545,545.2222'
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.atof(a)
545545.2222
>>> int(locale.atof(a))
545545
>>>

Example 2 -- European number conventions

In the majority of countries of the world, commas are used for decimal marks instead of periods. In this example with French locale, the comma is correctly handled as a decimal mark:

>>> import locale
>>> b = u'545,2222'
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')
'fr_FR'
>>> locale.atof(b)
545.2222

The method locale.atoi is also available, but the argument should be an integer.

Mark Chackerian
  • 19,405
  • 6
  • 103
  • 97
  • This seems like an ideal solution when you know if a float or int should be returned, but how can you get this to return an int only if an int was passed? For example, `x = '1'; locale.atof(x)` returns `1.0` when I actually want `1`. – user5359531 Jan 02 '19 at 18:33
  • 1
    Using Dino's method, I guess the answer would be to use something like this: `locale.atof(x) if locale.localeconv().get('decimal_point') in x else locale.atoi(x)` – user5359531 Jan 02 '19 at 18:52
  • I would recommend using Javier's method above (wrapping `locale.atoi` in a try and using `locale.atof` on exception -- it's probably more readable. – Mark Chackerian Jan 02 '19 at 19:08
81
float(x) if '.' in x else int(x)
S.Lott
  • 373,146
  • 78
  • 498
  • 766
Dino Viehland
  • 1,279
  • 7
  • 2
  • 24
    Note : be careful when dealing with money amount passed as strings, as some countries use "," as decimal separators – Ben G Jul 08 '11 at 11:17
  • 137
    @Emile: I wouldn't call "2e-3" an "extreme case". This answer is just broken. – jchl Sep 07 '11 at 10:05
  • 15
    @BenG DON'T manipulate money as a float. That's asking for trouble. Use decimal for money! (But your comment about ',' is still valid and important) – ToolmakerSteve Dec 13 '13 at 06:10
  • 5
    Don't forget that "not a number" (NaN) and +/- infinity is also valid float values. So `float("nan")` is a perfectly valid float value that the above answer wouldn't catch at all – Ronny Andersson Aug 23 '17 at 14:12
  • 5
    Easily breakable by an IP address - `192.168.0.1`; or `"This is not a good approach. :)"` – Todor Minakov Jan 13 '19 at 19:47
32

If you aren't averse to third-party modules, you could check out the fastnumbers module. It provides a function called fast_real that does exactly what this question is asking for and does it faster than a pure-Python implementation:

>>> from fastnumbers import fast_real
>>> fast_real("545.2222")
545.2222
>>> type(fast_real("545.2222"))
float
>>> fast_real("31")
31
>>> type(fast_real("31"))
int
SethMMorton
  • 41,116
  • 12
  • 64
  • 80
27

Users codelogic and harley are correct, but keep in mind if you know the string is an integer (for example, 545) you can call int("545") without first casting to float.

If your strings are in a list, you could use the map function as well.

>>> x = ["545.0", "545.6", "999.2"]
>>> map(float, x)
[545.0, 545.60000000000002, 999.20000000000005]
>>>

It is only good if they're all the same type.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
26

In Python, how can I parse a numeric string like "545.2222" to its corresponding float value, 542.2222? Or parse the string "31" to an integer, 31? I just want to know how to parse a float string to a float, and (separately) an int string to an int.

It's good that you ask to do these separately. If you're mixing them, you may be setting yourself up for problems later. The simple answer is:

"545.2222" to float:

>>> float("545.2222")
545.2222

"31" to an integer:

>>> int("31")
31

Other conversions, ints to and from strings and literals:

Conversions from various bases, and you should know the base in advance (10 is the default). Note you can prefix them with what Python expects for its literals (see below) or remove the prefix:

>>> int("0b11111", 2)
31
>>> int("11111", 2)
31
>>> int('0o37', 8)
31
>>> int('37', 8)
31
>>> int('0x1f', 16)
31
>>> int('1f', 16)
31

If you don't know the base in advance, but you do know they will have the correct prefix, Python can infer this for you if you pass 0 as the base:

>>> int("0b11111", 0)
31
>>> int('0o37', 0)
31
>>> int('0x1f', 0)
31

Non-Decimal (i.e. Integer) Literals from other Bases

If your motivation is to have your own code clearly represent hard-coded specific values, however, you may not need to convert from the bases - you can let Python do it for you automatically with the correct syntax.

You can use the apropos prefixes to get automatic conversion to integers with the following literals. These are valid for Python 2 and 3:

Binary, prefix 0b

>>> 0b11111
31

Octal, prefix 0o

>>> 0o37
31

Hexadecimal, prefix 0x

>>> 0x1f
31

This can be useful when describing binary flags, file permissions in code, or hex values for colors - for example, note no quotes:

>>> 0b10101 # binary flags
21
>>> 0o755 # read, write, execute perms for owner, read & ex for group & others
493
>>> 0xffffff # the color, white, max values for red, green, and blue
16777215

Making ambiguous Python 2 octals compatible with Python 3

If you see an integer that starts with a 0, in Python 2, this is (deprecated) octal syntax.

>>> 037
31

It is bad because it looks like the value should be 37. So in Python 3, it now raises a SyntaxError:

>>> 037
  File "<stdin>", line 1
    037
      ^
SyntaxError: invalid token

Convert your Python 2 octals to octals that work in both 2 and 3 with the 0o prefix:

>>> 0o37
31
Russia Must Remove Putin
  • 337,988
  • 84
  • 391
  • 326
21

The question seems a little bit old. But let me suggest a function, parseStr, which makes something similar, that is, returns integer or float and if a given ASCII string cannot be converted to none of them it returns it untouched. The code of course might be adjusted to do only what you want:

   >>> import string
   >>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \
   ...                      int(x) or x.isalnum() and x or \
   ...                      len(set(string.punctuation).intersection(x)) == 1 and \
   ...                      x.count('.') == 1 and float(x) or x
   >>> parseStr('123')
   123
   >>> parseStr('123.3')
   123.3
   >>> parseStr('3HC1')
   '3HC1'
   >>> parseStr('12.e5')
   1200000.0
   >>> parseStr('12$5')
   '12$5'
   >>> parseStr('12.2.2')
   '12.2.2'
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
krzym
  • 263
  • 2
  • 6
18

float("545.2222") and int(float("545.2222"))

codelogic
  • 69,114
  • 9
  • 58
  • 54
  • 1
    This will give you a float object if your string happens to be "0" or "0.0", rather than the int it gives for other valid numbers. – Brian Dec 19 '08 at 08:42
15

The YAML parser can help you figure out what datatype your string is. Use yaml.load(), and then you can use type(result) to test for type:

>>> import yaml

>>> a = "545.2222"
>>> result = yaml.load(a)
>>> result
545.22220000000004
>>> type(result)
<type 'float'>

>>> b = "31"
>>> result = yaml.load(b)
>>> result
31
>>> type(result)
<type 'int'>

>>> c = "HI"
>>> result = yaml.load(c)
>>> result
'HI'
>>> type(result)
<type 'str'>
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Rafe
  • 1,679
  • 19
  • 31
  • This is a great answer (or `json` or whatever your favorite is): we all recognize that proper conversion is non-trivial. So find a widely adopted library that manages this for you. :) – Mike Williamson Sep 10 '21 at 09:00
  • JSON can work great but will just raise a TypeError if a string is passed, so needs some custom handling or pre-checks to avoid some attempts. Like I some regexp: https://stackoverflow.com/a/69790897/1236083 – Rafe Oct 31 '21 at 21:57
13

I use this function for that

import ast

def parse_str(s):
   try:
      return ast.literal_eval(str(s))
   except:
      return

It will convert the string to its type

value = parse_str('1')  # Returns Integer
value = parse_str('1.5')  # Returns Float
Shameem
  • 2,374
  • 15
  • 20
12
def get_int_or_float(v):
    number_as_float = float(v)
    number_as_int = int(number_as_float)
    return number_as_int if number_as_float == number_as_int else number_as_float
Totoro
  • 861
  • 9
  • 10
  • 1
    Why would you raise in your `except` section if you are doing nothing there? float() would raise for you. – Greg0ry Mar 19 '16 at 20:30
  • 1
    you are right I guess I copied and paste from a functionality that I was raising a particular exception. will edit. thanks – Totoro Nov 02 '16 at 15:18
  • 1
    This will try to parse a string and return either `int` or `float` depending on what the string represents. It might rise parsing exceptions or [have some unexpected behaviour][1]. – Kuzeko May 18 '17 at 07:28
9
def num(s):
    """num(s)
    num(3),num(3.7)-->3
    num('3')-->3, num('3.7')-->3.7
    num('3,700')-->ValueError
    num('3a'),num('a3'),-->ValueError
    num('3e4') --> 30000.0
    """
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            raise ValueError('argument is not a string of number')
Georgy
  • 9,972
  • 7
  • 57
  • 66
Jerry T
  • 1,397
  • 17
  • 16
6

You need to take into account rounding to do this properly.

i.e. - int(5.1) => 5 int(5.6) => 5 -- wrong, should be 6 so we do int(5.6 + 0.5) => 6

def convert(n):
    try:
        return int(n)
    except ValueError:
        return float(n + 0.5)
Guy Avraham
  • 3,156
  • 3
  • 36
  • 46
Nick
  • 26,908
  • 12
  • 57
  • 71
  • 4
    Good point. That causes inflation, though, so [Python 3](http://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior) and [other modern languages](http://stackoverflow.com/questions/311696/why-does-net-use-bankers-rounding-as-default) use banker's rounding. – Cees Timmerman Oct 04 '12 at 12:58
  • 2
    This answer is wrong (as originally written). It muddles the two cases of `int` and `float`. And it will give an exception, when `n` is a string, as OP desired. Maybe you meant: **When** an `int` result is desired, `round` should be done AFTER conversion to float. If the function should ALWAYS return an int, then you don't need the except part -- the entire function body can be `int(round(float(input)))`. If the function should return an int if possible, otherwise a float, then javier's original solution is correct! – ToolmakerSteve Dec 13 '13 at 06:02
  • ValueError: could not convert string to float – Avi Thour May 01 '22 at 23:04
6

I am surprised nobody mentioned regex because sometimes string must be prepared and normalized before casting to number

import re
def parseNumber(value, as_int=False):
    try:
        number = float(re.sub('[^.\-\d]', '', value))
        if as_int:
            return int(number + 0.5)
        else:
            return number
    except ValueError:
        return float('nan')  # or None if you wish

usage:

parseNumber('13,345')
> 13345.0

parseNumber('- 123 000')
> -123000.0

parseNumber('99999\n')
> 99999.0

and by the way, something to verify you have a number:

import numbers
def is_number(value):
    return isinstance(value, numbers.Number)
    # will work with int, float, long, Decimal
Sławomir Lenart
  • 6,284
  • 3
  • 38
  • 53
6

To typecast in Python use the constructor functions of the type, passing the string (or whatever value you are trying to cast) as a parameter.

For example:

>>>float("23.333")
   23.333

Behind the scenes, Python is calling the objects __float__ method, which should return a float representation of the parameter. This is especially powerful, as you can define your own types (using classes) with a __float__ method so that it can be casted into a float using float(myobject).

Guy Avraham
  • 3,156
  • 3
  • 36
  • 46
kCODINGeroo
  • 414
  • 4
  • 13
6

Pass your string to this function:

def string_to_number(str):
  if("." in str):
    try:
      res = float(str)
    except:
      res = str  
  elif(str.isdigit()):
    res = int(str)
  else:
    res = str
  return(res)

It will return int, float or string depending on what was passed.

string that is an int

print(type(string_to_number("124")))
<class 'int'>

string that is a float

print(type(string_to_number("12.4")))
<class 'float'>

string that is a string

print(type(string_to_number("hello")))
<class 'str'>

string that looks like a float

print(type(string_to_number("hel.lo")))
<class 'str'>
Cybernetic
  • 11,188
  • 15
  • 76
  • 114
  • 2
    when looking at the name `string_to_number` I wouldn't expect it to return a string. I would expect it to raise an Exception if the input can't be parsed – Neuron - Freedom for Ukraine Jul 29 '21 at 12:26
  • I don't think it's a controversial opinion that a method called string_to_number should not return a string. I downvoted because the function is either poorly named or it's behaviour is wrong. also, there is no need to be passive aggressive. We can talk this out in a professional fashion – Neuron - Freedom for Ukraine Jul 30 '21 at 08:56
5

Handles hex, octal, binary, decimal, and float

This solution will handle all of the string conventions for numbers (all that I know about).

def to_number(n):
    ''' Convert any number representation to a number 
    This covers: float, decimal, hex, and octal numbers.
    '''

    try:
        return int(str(n), 0)
    except:
        try:
            # python 3 doesn't accept "010" as a valid octal.  You must use the
            # '0o' prefix
            return int('0o' + n, 0)
        except:
            return float(n)

This test case output illustrates what I'm talking about.

======================== CAPTURED OUTPUT =========================
to_number(3735928559)   = 3735928559 == 3735928559
to_number("0xFEEDFACE") = 4277009102 == 4277009102
to_number("0x0")        =          0 ==          0
to_number(100)          =        100 ==        100
to_number("42")         =         42 ==         42
to_number(8)            =          8 ==          8
to_number("0o20")       =         16 ==         16
to_number("020")        =         16 ==         16
to_number(3.14)         =       3.14 ==       3.14
to_number("2.72")       =       2.72 ==       2.72
to_number("1e3")        =     1000.0 ==       1000
to_number(0.001)        =      0.001 ==      0.001
to_number("0xA")        =         10 ==         10
to_number("012")        =         10 ==         10
to_number("0o12")       =         10 ==         10
to_number("0b01010")    =         10 ==         10
to_number("10")         =         10 ==         10
to_number("10.0")       =       10.0 ==         10
to_number("1e1")        =       10.0 ==         10

Here is the test:

class test_to_number(unittest.TestCase):

    def test_hex(self):
        # All of the following should be converted to an integer
        #
        values = [

                 #          HEX
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (0xDEADBEEF  , 3735928559), # Hex
                ("0xFEEDFACE", 4277009102), # Hex
                ("0x0"       ,          0), # Hex

                 #        Decimals
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (100         ,        100), # Decimal
                ("42"        ,         42), # Decimal
            ]



        values += [
                 #        Octals
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (0o10        ,          8), # Octal
                ("0o20"      ,         16), # Octal
                ("020"       ,         16), # Octal
            ]


        values += [
                 #        Floats
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                (3.14        ,       3.14), # Float
                ("2.72"      ,       2.72), # Float
                ("1e3"       ,       1000), # Float
                (1e-3        ,      0.001), # Float
            ]

        values += [
                 #        All ints
                 # ----------------------
                 # Input     |   Expected
                 # ----------------------
                ("0xA"       ,         10), 
                ("012"       ,         10), 
                ("0o12"      ,         10), 
                ("0b01010"   ,         10), 
                ("10"        ,         10), 
                ("10.0"      ,         10), 
                ("1e1"       ,         10), 
            ]

        for _input, expected in values:
            value = to_number(_input)

            if isinstance(_input, str):
                cmd = 'to_number("{}")'.format(_input)
            else:
                cmd = 'to_number({})'.format(_input)

            print("{:23} = {:10} == {:10}".format(cmd, value, expected))
            self.assertEqual(value, expected)
shrewmouse
  • 4,387
  • 3
  • 32
  • 38
5
a = int(float(a)) if int(float(a)) == float(a) else float(a)
bougui
  • 3,199
  • 3
  • 20
  • 26
4

You could use json.loads:

>>> import json
>>> json.loads('123.456')
123.456
>>> type(_)
<class 'float'>
>>> 

As you can see it becomes a type of float.

U12-Forward
  • 65,118
  • 12
  • 70
  • 89
3

This is a corrected version of https://stackoverflow.com/a/33017514/5973334

This will try to parse a string and return either int or float depending on what the string represents. It might rise parsing exceptions or have some unexpected behaviour.

  def get_int_or_float(v):
        number_as_float = float(v)
        number_as_int = int(number_as_float)
        return number_as_int if number_as_float == number_as_int else 
        number_as_float
Community
  • 1
  • 1
Kuzeko
  • 1,365
  • 14
  • 35
2

this is an old question and got already a lot of answers. but if you are dealing with mixed integers and floats and want a consistent way to deal with your mixed data, here is my solution with the proper docstring:

def parse_num(candidate):
    """parse string to number if possible
    work equally well with negative and positive numbers, integers and floats.

    Args:
        candidate (str): string to convert

    Returns:
        float | int | None: float or int if possible otherwise None
    """
    try:
        float_value = float(candidate)
    except ValueError:
        return None

    # optional part if you prefer int to float when decimal part is 0 
    if float_value.is_integer():
        return int(float_value)
    # end of the optional part

    return float_value

# test
candidates = ['34.77', '-13', 'jh', '8990', '76_3234_54']
res_list = list(map(parse_num, candidates))
print('Before:')
print(candidates)
print('After:')
print(res_list)

output:

Before:
['34.77', '-13', 'jh', '8990', '76_3234_54']
After:
[34.77, -13, None, 8990, 76323454]
Sameh Farouk
  • 489
  • 3
  • 7
1

Use:

def num(s):
    try:
        for each in s:
            yield int(each)
    except ValueError:
        yield float(each)
a = num(["123.55","345","44"])
print a.next()
print a.next()

This is the most Pythonic way I could come up with.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
SeasonalShot
  • 1,988
  • 2
  • 29
  • 47
  • The generator stops after the first interpretation of `float`. The `try`…`catch` block should probably be inside the `for` loop. – musiphil May 02 '19 at 19:43
0

Use:

>>> str_float = "545.2222"
>>> float(str_float)
545.2222
>>> type(_) # Check its type
<type 'float'>

>>> str_int = "31"
>>> int(str_int)
31
>>> type(_) # Check its type
<type 'int'>
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
0

This is a function which will convert any object (not just str) to int or float, based on if the actual string supplied looks like int or float. Further if it's an object which has both __float and __int__ methods, it defaults to using __float__

def conv_to_num(x, num_type='asis'):
    '''Converts an object to a number if possible.
    num_type: int, float, 'asis'
    Defaults to floating point in case of ambiguity.
    '''
    import numbers

    is_num, is_str, is_other = [False]*3

    if isinstance(x, numbers.Number):
        is_num = True
    elif isinstance(x, str):
        is_str = True

    is_other = not any([is_num, is_str])

    if is_num:
        res = x
    elif is_str:
        is_float, is_int, is_char = [False]*3
        try:
            res = float(x)
            if '.' in x:
                is_float = True
            else:
                is_int = True
        except ValueError:
            res = x
            is_char = True

    else:
        if num_type == 'asis':
            funcs = [int, float]
        else:
            funcs = [num_type]

        for func in funcs:
            try:
                res = func(x)
                break
            except TypeError:
                continue
        else:
            res = x
Abhishek Bhatia
  • 457
  • 4
  • 9
0

By using int and float methods we can convert a string to integer and floats.

s="45.8"
print(float(s))

y='67'
print(int(y))
SHR
  • 7,570
  • 9
  • 36
  • 56
  • 2
    This answer doesn't add anything new. See, for example, [this answer](https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int/31588754#31588754) which gives the same information and more. – Georgy May 26 '20 at 13:56
0

for number and char together :

string_for_int = "498 results should get"
string_for_float = "498.45645765 results should get"

first import re:

 import re

 #for get integer part:
 print(int(re.search(r'\d+', string_for_int).group())) #498

 #for get float part:
 print(float(re.search(r'\d+\.\d+', string_for_float).group())) #498.45645765

for easy model :

value1 = "10"
value2 = "10.2"
print(int(value1)) #10
print(float(value2)) #10.2
mamal
  • 1,279
  • 13
  • 11
-12

Here's another interpretation of your question (hint: it's vague). It's possible you're looking for something like this:

def parseIntOrFloat( aString ):
    return eval( aString )

It works like this...

>>> parseIntOrFloat("545.2222")
545.22220000000004
>>> parseIntOrFloat("545")
545

Theoretically, there's an injection vulnerability. The string could, for example be "import os; os.abort()". Without any background on where the string comes from, however, the possibility is theoretical speculation. Since the question is vague, it's not at all clear if this vulnerability actually exists or not.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
S.Lott
  • 373,146
  • 78
  • 498
  • 766