Skip to content Skip to sidebar Skip to footer

How To Check Last Digit Of Number

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 put print number[:

Solution 1:

Remainder when dividing by 10, as in

numericVariable % 10

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

Solution 2:

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).

Solution 3:

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

n = 56789lastdigit = 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

Solution 4:

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

Solution 5:

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!

Post a Comment for "How To Check Last Digit Of Number"