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.
Thanks a lot
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.
Thanks a lot
Just take mod 10:
Int32 lastNumber = num % 10;
It's just the number modulo 10. For example in C
int i = 1232123; int lastdigit = (i % 10);
Here's the brute force way that sacrifices efficiency for obviousness:
int n = 1232123; int last = Convert.ToInt32(n.ToString() .AsEnumerable() .Last() .ToString());
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 "fife"; case 6: return "six"; case 7: return "seven"; case 8: return "eight"; case 9: return "nine"; }
Another way is..
var digit = Convert.ToString(1234); var lastDigit = digit.Substring(digit.Length - 1);
The best would be:
Math.Abs(num % 10);
Cause num % 10
will give you negative result for negative numbers