mns
mns

Reputation: 683

How to get the last digit of a number

How to get the last digit of a number? e.g. if 1232123, 3 will be the result

Some efficient logic I want so that it is easy for results having big numbers.
After the final number I get, I need to some processing in it.

Upvotes: 36

Views: 82190

Answers (6)

Atanas Tankov
Atanas Tankov

Reputation: 31

The best way to do this is int lastNumber = (your number) % 10;
And if you want to return the last digit as string you can do this

switch (number % 10)
{
    case 0:
        return "zero";
    case 1:
        return "one";
    case 2:
        return "two";
    case 3:
        return "three";
    case 4:
        return "four";
    case 5:
        return "five";
    case 6:
        return "six";
    case 7:
        return "seven";
    case 8:
        return "eight";
    case 9:
        return "nine";
}

Upvotes: 3

acrilige
acrilige

Reputation: 2456

Just take mod 10:

Int32 lastNumber = num % 10;

One could use Math.Abs if one's going to deal with negative numbers. Like so:

Int32 lastNumber = Math.Abs(num) % 10;

Upvotes: 80

Chilli
Chilli

Reputation: 337

The best would be:

Math.Abs(num % 10);

Cause num % 10 will give you negative result for negative numbers

Upvotes: 5

Adarsh Babu PR
Adarsh Babu PR

Reputation: 197

Another way is..

var digit = Convert.ToString(1234);
var lastDigit = digit.Substring(digit.Length - 1);

Upvotes: 1

Aaron Anodide
Aaron Anodide

Reputation: 17186

Here's the brute force way that sacrifices efficiency for obviousness:

int n = 1232123;
int last = Convert.ToInt32(n.ToString()
                            .AsEnumerable()
                            .Last()
                            .ToString());

Upvotes: 12

Stochastically
Stochastically

Reputation: 7836

It's just the number modulo 10. For example in C

int i = 1232123;
int lastdigit = (i % 10);

Upvotes: 17

Related Questions