Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
general conversion to int
#1
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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.
Reply
#3
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
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).
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  General query regarding conversion of dict to class object saisankalpj 0 1,890 Jan-16-2019, 01:58 PM
Last Post: saisankalpj

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020