Home > OS >  Is there a math formula for converting string into integer on my own?
Is there a math formula for converting string into integer on my own?

Time:03-12

I am creating this code for a project at my school, the current formula I have for adding an integer to the end of a number is: "curnumber = curnumber (integer - curnumber)", kind of like if you want x to be 13 and the current number is 2, you'd do something like "x = x (13 - 2)" and it'd return the number but I don't know how to combine the numbers, it's really confusing, I'm able to get the number from a single character using this code:
def singleint(num):

    int_ = 0
    if num == '0':
        int_ = 0
    elif num == '1':
        int_ = 1
    elif num == '2':
        int_ = 2
    elif num == '3':
        int_ = 3
    elif num == '4':
        int_ = 4
    elif num == '5':
        int_ = 5
    elif num == '6':
        int_ = 6
    elif num == '7':
        int_ = 7
    elif num == '8':
        int_ = 8
    elif num == '9':
        int_ = 9
    return int_`

and my total current code is:

def singleint(num):
    int_ = 0
    if num == '0':
        int_ = 0
    elif num == '1':
        int_ = 1
    elif num == '2':
        int_ = 2
    elif num == '3':
        int_ = 3
    elif num == '4':
        int_ = 4
    elif num == '5':
        int_ = 5
    elif num == '6':
        int_ = 6
    elif num == '7':
        int_ = 7
    elif num == '8':
        int_ = 8
    elif num == '9':
        int_ = 9
    return int_

def tonumber(str_):
    num = 0
    x = 0
    for char in list(str(str_)):
        c = singleint(char)
        print(type(c))
        new = (c - num)
        num = num   new
        x  = 1
    return num

print(str(tonumber(192)))

I really need help with this, thanks

CodePudding user response:

I'm not 100% sure what you're asking here but I think the answer to your question is:

int(num)

That'll convert the string to an integer.

CodePudding user response:

Try to see if all the characters in a string is numeric by using isnumeric() method, and if true, then use int() to convert it.

def convert_number(string_format):
    if string_format.isnumeric():
         return int(string_format)
    else:
         return None
  • Related