How to check last digit of number

前端 未结 8 1891
情歌与酒
情歌与酒 2020-12-06 04:21

Is there a way to get the last digit of a number. I am trying to find variables that end with \"1\" like 1,11,21,31,41,etc..

If I use a text variable I can simply pu

相关标签:
8条回答
  • 2020-12-06 04:46

    So you want to access the digits in a integer like elements in a list; easiest way I can think of is:

    n = 56789
    lastdigit = int(repr(n)[-1])
    # >  9
    

    Convert n into a string, accessing last element then use int constructor to convert back into integer.

    For a Floating point number:

    n = 179.123
    fstr = repr(n)
    signif_digits, fract_digits = fstr.split('.')
    # >  ['179', '123']
    signif_lastdigit = int(signif_digits[-1])
    # >  9
    
    0 讨论(0)
  • 2020-12-06 04:46

    Convert to string first:

    oldint = 10101
    newint = int(str(oldint)[-1:]) 
    
    0 讨论(0)
  • 2020-12-06 04:51

    I can't add a comment yet, but I wanted to iterate and expand on what Jim Garrison said

    Remainder when dividing by 10, as in numericVariable % 10

    This only works for positive numbers. -12%10 yields 8

    While modulus (%) is working as intended, throw on an absolute value to use the modulus in this situation.

    abs(numericVariable) % 10
    
    0 讨论(0)
  • 2020-12-06 04:54

    Use the modulus operator with 10:

    num = 11
    if num % 10 == 1:
        print 'Whee!'
    

    This gives the remainder when dividing by 10, which will always be the last digit (when the number is positive).

    0 讨论(0)
  • 2020-12-06 04:57

    Remainder when dividing by 10, as in

    numericVariable % 10
    

    This only works for positive numbers. -12%10 yields 8

    0 讨论(0)
  • 2020-12-06 05:01

    Lostsoul, this should work:

        number = int(10)
    #The variable number can also be a float or double, and I think it should still work.
    lastDigit = int(repr(number)[-1])
    #This gives the last digit of the variable "number." 
    if lastDigit == 1 : 
        print("The number ends in 1!")
    

    Instead of the print statement at the end, you can add code to do what you need to with numbers ending in 1.

    Hope it helped!

    0 讨论(0)
提交回复
热议问题