Python Forum
general conversion to int - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: general conversion to int (/thread-12076.html)



general conversion to int - Skaperen - Aug-08-2018

how can i have a single simple expression convert an object to an int or raise an exception only if it cannot be converted to an int? valid objects include floats, decimal.Decimal, and strings of numbers in some base specified by its prefix. int(s) assumes decimal unless coded as int(s,0) but then if s is a float it raises an exception. i just want the whole part of the real part of anything Python can convert to a number by any means.


RE: general conversion to int - Vysero - Aug-08-2018

I probably don't understand the whole scope of your questing but here's what I am thinking and its a bit more general:

def force_to_int(input, new_output=None):
  try:
    return int(input)
  except Exception:
    return new_output
This type of catch-all isn't great but since objects can raise exceptions when executing __int__() than any exception is possible; even if TypeError and ValueError are really the only likely ones.


RE: general conversion to int - DeaD_EyE - Aug-08-2018

Do you want something like this?
def to_int(x=0, base=10):
    """
    to_int([x]) -> integer
    to_int(x, base=10) -> integer
    
    Convert a number or string to an integer, or return 0 if no arguments
    are given.   If x is a number, return x.__int__().  For floating point
    numbers, strings and decimal.Decimal, this truncates towards zero.
    
    The base defaults to 10.  Valid bases are 0 and 2-36.
    Base 0 means to interpret the base from x as an integer literal.
    """
    try:
        return int(x, base)
    except (ValueError, TypeError) as e:
        pass
    if isinstance(x, (bytes, bytearray)):
        return int(x.partition(b'.')[0], base)
    else:
        return int(str(x).partition('.')[0], base)
This allows silly things like this:

def test():
    values = [
        ('1.0', 0),
        ('0b101.11', 0),
        ('0xFF.1', 0),
        (16.1, 16),
        ('16.55', 16),
        ('FF.ABC', 16),
    ]
    for x, base in values:
        print(f'{x!s:<10} type: {type(x)!s:<20} base: {base:<10} ->', to_int(x, base))

test()
Output:
1.0 type: <class 'str'> base: 0 -> 1 0b101.11 type: <class 'str'> base: 0 -> 5 0xFF.1 type: <class 'str'> base: 0 -> 255 16.1 type: <class 'float'> base: 16 -> 22 16.55 type: <class 'str'> base: 16 -> 22 FF.ABC type: <class 'str'> base: 16 -> 255
Good luck Dance


RE: general conversion to int - Skaperen - Aug-09-2018

some things can only be converted to int by a call like int(thing), such as a float object. other things can only be converted to int by a call like int(thing,0), such as a string that has an unknown base specified in the prefix of the string such as '0xff' or '0o377' or '0b11111111' or just '255'. float does not work in int(thing,0) and most of those strings don't work in int(thing).